Skip to content

Commit 7be705e

Browse files
vuanhphungIsaac
andauthored
feat: add rowMode option to keep columns with duplicate names (#591)
* feat: add rowMode option to return rows as arrays Rows keyed by column name lose data when columns share a name (e.g. SELECT carat AS a, color AS a). rowMode: 'array' returns each row as values in schema order on the Thrift JSON, Arrow, CloudFetch and kernel paths. The default object mode is unchanged but now warns once per result set when it detects duplicate column names. Fixes #118 Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> * test: add e2e coverage for rowMode Cover duplicate-alias rows in array mode on Thrift column-based, inline Arrow (LZ4) and CloudFetch results, staging statements in array mode, and the kernel and Thrift backends in the kernel parity spec. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> * feat: export RowMode from the package entry point Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> --------- Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com>
1 parent f341c27 commit 7be705e

14 files changed

Lines changed: 788 additions & 21 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
- Add `Symbol.asyncDispose` to clients, sessions, and operations, delegating to `close()`. Use `asyncDisposable()` with interface-typed results in TypeScript; existing interfaces and factory return types remain unchanged. (#331)
1010
- Thrift `ExecuteStatement` requests are now retried when the connection fails before the request is sent (`ECONNREFUSED`, `ENOTFOUND`, `EAI_AGAIN`), within the existing `retryMaxAttempts` / `retriesTimeout` budget; once retries run out, the original connection error is thrown. Failures after the request may have reached the server are still not retried, so a statement can't run twice. (#458)
1111
- Add the `https` connection option: set `https: false` to connect to `host` over plain HTTP (port 80 by default), for example through a trusted local reverse proxy. HTTPS remains the default, and plain HTTP should only be used on a trusted local or private link. (#503)
12+
- Add the `rowMode` option to `executeStatement()`: `rowMode: 'array'` returns each row as an array of values in column order, so columns with the same name (e.g. `SELECT carat AS a, color AS a`) are no longer lost; the default `'object'` rows are unchanged, and the driver now logs a warning when a result has duplicate column names in object mode. (#118)
1213
- CloudFetch retry-exhaustion errors now identify the download and the last failure: the `RetryError` message reads `CloudFetch result download failed: <original message> (last error: <cause>)`. `<cause>` is `HTTP <status>: <statusText>` (or `HTTP <status>` when the status text is empty) for HTTP failures, and `network error <code>`, `network error (<type>)` (e.g. `aborted`, when there is no `code`) or a bare `network error` for network failures (the raw network-error message, which can contain the presigned URL, is not copied). If no cause can be determined, the ` (last error: …)` suffix is omitted. The `RetryError` instance, `errorCode` and `payload` (including the node-fetch `Request` / `Response`) are unchanged. (#471)
1314
- Report untyped NULL columns as STRING in kernel result metadata, matching Thrift. (#470)
1415
- `IOperation.close()` no longer throws when the close request fails after the operation has finished (for example, once its results were read, or when the execute response already reported completion): the failure is logged as a warning and reported in the returned status's `info`, and the operation is still closed locally. Closing an operation that hasn't finished still throws on failure. (#480)

‎lib/DBSQLSession.ts‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ import { numberToInt64 as numberToInt64Impl } from './thrift-backend/ThriftSessi
3131
import { safeEmit } from './telemetry/telemetryUtils';
3232
// Declares `Symbol.asyncDispose` for the emitted typings of `[Symbol.asyncDispose]()` below
3333
import './contracts/asyncDispose';
34+
import { ResultMetadata } from './contracts/ResultMetadata';
35+
import { getSchemaColumns } from './result/utils';
3436

3537
// Explicitly promisify a callback-style `pipeline` because `node:stream/promises` is not available in Node 14
3638
const pipeline = util.promisify(stream.pipeline);
@@ -93,6 +95,9 @@ export default class DBSQLSession implements IDBSQLSession {
9395
* const operation = await session.executeStatement(query);
9496
*/
9597
public async executeStatement(statement: string, options: ExecuteStatementOptions = {}): Promise<IOperation> {
98+
if (options.rowMode !== undefined && options.rowMode !== 'object' && options.rowMode !== 'array') {
99+
throw new HiveDriverError(`Unsupported rowMode: ${options.rowMode}. Expected 'object' or 'array'.`);
100+
}
96101
const opBackend = await this.runBackend(() => this.backend.executeStatement(statement, options));
97102
const operation = this.wrapOperation(opBackend);
98103

@@ -109,13 +114,17 @@ export default class DBSQLSession implements IDBSQLSession {
109114
const allowedLocalPath = Array.isArray(options.stagingAllowedLocalPath)
110115
? options.stagingAllowedLocalPath
111116
: [options.stagingAllowedLocalPath];
112-
return this.handleStagingOperation(operation, allowedLocalPath);
117+
return this.handleStagingOperation(operation, allowedLocalPath, metadata);
113118
}
114119
}
115120
return operation;
116121
}
117122

118-
private async handleStagingOperation(operation: IOperation, allowedLocalPath: Array<string>): Promise<IOperation> {
123+
private async handleStagingOperation(
124+
operation: IOperation,
125+
allowedLocalPath: Array<string>,
126+
metadata: ResultMetadata,
127+
): Promise<IOperation> {
119128
type StagingResponse = {
120129
presignedUrl: string;
121130
localFile?: string;
@@ -126,7 +135,15 @@ export default class DBSQLSession implements IDBSQLSession {
126135
if (rows.length !== 1) {
127136
throw new StagingError('Staging operation: expected only one row in result');
128137
}
129-
const row = rows[0] as StagingResponse;
138+
let row = rows[0] as StagingResponse;
139+
// `rowMode: 'array'` returns positional rows; key them by column name.
140+
if (Array.isArray(row)) {
141+
const values: Array<unknown> = row;
142+
row = getSchemaColumns(metadata.schema).reduce(
143+
(result, column, i) => ({ ...result, [column.columnName]: values[i] }),
144+
{} as StagingResponse,
145+
);
146+
}
130147

131148
if (row.localFile !== undefined) {
132149
let allowOperation = false;

‎lib/contracts/IDBSQLSession.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,15 @@ import Status from '../dto/Status';
44
import InfoValue from '../dto/InfoValue';
55
import { DBSQLParameter, DBSQLParameterValue } from '../DBSQLParameter';
66

7+
/**
8+
* Shape of the rows returned by a statement's fetch methods:
9+
* - `'object'` (default): each row is an object keyed by column name. Columns
10+
* that share a name (e.g. `SELECT a.id, b.id`) overwrite each other.
11+
* - `'array'`: each row is an array of values in result-schema order, so every
12+
* column is kept. Use `getResultMetadata()` / `getSchema()` for column names.
13+
*/
14+
export type RowMode = 'object' | 'array';
15+
716
export type ExecuteStatementOptions = {
817
/**
918
* The number of seconds after which the query will time out on the server.
@@ -50,6 +59,11 @@ export type ExecuteStatementOptions = {
5059
* `query_tags` key). Ignored by the Thrift backend.
5160
*/
5261
statementConf?: Record<string, string>;
62+
/**
63+
* Row shape returned by this statement's `fetchChunk` / `fetchAll` / iterators.
64+
* Defaults to `'object'`; see {@link RowMode}.
65+
*/
66+
rowMode?: RowMode;
5367
};
5468

5569
export type TypeInfoRequest = {

‎lib/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { LogLevel } from './contracts/IDBSQLLogger';
2222

2323
// Re-export types for TypeScript users
2424
export type { default as ITokenProvider } from './connection/auth/tokenProvider/ITokenProvider';
25+
export type { RowMode } from './contracts/IDBSQLSession';
2526

2627
export { default as asyncDisposable } from './asyncDisposable';
2728
export type { AsyncDisposableResource } from './asyncDisposable';

‎lib/kernel/KernelOperationBackend.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import { OperationStatus, OperationState } from '../contracts/OperationStatus';
4343
import { ResultMetadata, ResultFormat } from '../contracts/ResultMetadata';
4444
import IClientContext from '../contracts/IClientContext';
4545
import { LogLevel } from '../contracts/IDBSQLLogger';
46+
import { RowMode } from '../contracts/IDBSQLSession';
4647
import Status from '../dto/Status';
4748
import HiveDriverError from '../errors/HiveDriverError';
4849
import OperationStateError, { OperationStateErrorCode } from '../errors/OperationStateError';
@@ -167,6 +168,8 @@ export interface KernelOperationBackendOptions {
167168
* handle exposes one, else a fresh UUIDv4.
168169
*/
169170
id?: string;
171+
/** Row shape returned by `fetchChunk`; defaults to `'object'`. */
172+
rowMode?: RowMode;
170173
}
171174

172175
export default class KernelOperationBackend implements IOperationBackend {
@@ -202,6 +205,8 @@ export default class KernelOperationBackend implements IOperationBackend {
202205

203206
private readonly lifecycle: KernelOperationLifecycleState = createLifecycleState();
204207

208+
private readonly rowMode?: RowMode;
209+
205210
private resultSlicer?: ResultSlicer<any>;
206211

207212
private resultsProvider?: KernelResultsProvider;
@@ -220,7 +225,14 @@ export default class KernelOperationBackend implements IOperationBackend {
220225
// synchronous terminal-state accessor, so the observed success is retained.
221226
private asyncSucceeded = false;
222227

223-
constructor({ asyncStatement, statement, cancellableExecution, context, id }: KernelOperationBackendOptions) {
228+
constructor({
229+
asyncStatement,
230+
statement,
231+
cancellableExecution,
232+
context,
233+
id,
234+
rowMode,
235+
}: KernelOperationBackendOptions) {
224236
// Exactly one of the three handle kinds must be supplied.
225237
const providedCount =
226238
(asyncStatement !== undefined ? 1 : 0) +
@@ -249,6 +261,7 @@ export default class KernelOperationBackend implements IOperationBackend {
249261
}
250262
: ((asyncStatement ?? statement) as KernelStatementHandle);
251263
this.context = context;
264+
this.rowMode = rowMode;
252265
this._id =
253266
id ?? asyncStatement?.statementId ?? statement?.statementId ?? cancellableExecution?.statementId ?? uuidv4();
254267
}
@@ -819,6 +832,7 @@ export default class KernelOperationBackend implements IOperationBackend {
819832
const converter = new ArrowResultConverter(this.context, this.resultsProvider, metadata, {
820833
preserveBigNumericPrecision: this.context.getConfig().preserveBigNumericPrecision ?? false,
821834
disableRowMaterialization: this.context.getConfig().disableRowMaterialization ?? false,
835+
rowMode: this.rowMode,
822836
});
823837
this.resultSlicer = new ResultSlicer(this.context, converter);
824838
return this.resultSlicer;

‎lib/kernel/KernelSessionBackend.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -257,9 +257,9 @@ export default class KernelSessionBackend implements ISessionBackend {
257257
// Feature-detect the arm via a type guard: only the Running `AsyncStatement`
258258
// exposes `awaitResult`; the terminal `Statement` (Completed arm) does not.
259259
if (isKernelAsyncStatement(direct)) {
260-
return new KernelOperationBackend({ asyncStatement: direct, context: this.context });
260+
return new KernelOperationBackend({ asyncStatement: direct, context: this.context, rowMode: options.rowMode });
261261
}
262-
return new KernelOperationBackend({ statement: direct, context: this.context });
262+
return new KernelOperationBackend({ statement: direct, context: this.context, rowMode: options.rowMode });
263263
}
264264

265265
// Async path: submit (`wait_timeout=0s`) returns a pending handle the
@@ -279,6 +279,7 @@ export default class KernelSessionBackend implements ISessionBackend {
279279
return new KernelOperationBackend({
280280
asyncStatement: asyncStatement!,
281281
context: this.context,
282+
rowMode: options.rowMode,
282283
});
283284
}
284285

‎lib/result/ArrowResultConverter.ts‎

Lines changed: 60 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,10 @@ import {
1717
} from 'apache-arrow';
1818
import { TTableSchema, TColumnDesc, TTypeId } from '../../thrift/TCLIService_types';
1919
import IClientContext from '../contracts/IClientContext';
20+
import { RowMode } from '../contracts/IDBSQLSession';
2021
import HiveDriverError from '../errors/HiveDriverError';
2122
import IResultsProvider, { ResultsProviderFetchNextOptions } from './IResultsProvider';
22-
import { ArrowBatch, getSchemaColumns, convertThriftValue } from './utils';
23+
import { ArrowBatch, getSchemaColumns, convertThriftValue, warnOnDuplicateColumnNames } from './utils';
2324

2425
const { isArrowBigNumSymbol, bigNumToBigInt } = arrowUtils;
2526

@@ -208,6 +209,8 @@ export default class ArrowResultConverter implements IResultsProvider<Array<any>
208209
// (only the row count is meaningful). See `ConnectionOptions.disableRowMaterialization`.
209210
private readonly disableRowMaterialization: boolean;
210211

212+
private readonly rowMode: RowMode;
213+
211214
private recordBatchReader?: IterableIterator<RecordBatch<TypeMap>>;
212215

213216
// Remaining rows in current Arrow batch (not the record batch!)
@@ -232,13 +235,18 @@ export default class ArrowResultConverter implements IResultsProvider<Array<any>
232235
{
233236
preserveBigNumericPrecision = false,
234237
disableRowMaterialization = false,
235-
}: { preserveBigNumericPrecision?: boolean; disableRowMaterialization?: boolean } = {},
238+
rowMode = 'object',
239+
}: { preserveBigNumericPrecision?: boolean; disableRowMaterialization?: boolean; rowMode?: RowMode } = {},
236240
) {
237241
this.context = context;
238242
this.source = source;
239243
this.schema = getSchemaColumns(schema);
240244
this.preserveBigNumericPrecision = preserveBigNumericPrecision;
241245
this.disableRowMaterialization = disableRowMaterialization;
246+
this.rowMode = rowMode;
247+
if (rowMode === 'object' && !disableRowMaterialization) {
248+
warnOnDuplicateColumnNames(context, this.schema);
249+
}
242250
}
243251

244252
public async hasMore() {
@@ -268,15 +276,21 @@ export default class ArrowResultConverter implements IResultsProvider<Array<any>
268276

269277
if (this.prefetchedRecordBatch) {
270278
// Consume a record batch fetched during previous call to `fetchNext`
271-
const table = new Table(this.prefetchedRecordBatch);
279+
const batch = this.prefetchedRecordBatch;
272280
this.prefetchedRecordBatch = undefined;
273281
// Get table rows, but not more than remaining count. When materialization
274282
// is disabled, skip `toArray()`/`getRows()` and return `null` placeholders
275283
// (filled, not sparse, so `fetchAll`'s `.flat()` keeps the count).
276-
const batchRows = Math.min(table.numRows, this.remainingRows);
277-
const result = this.disableRowMaterialization
278-
? new Array(batchRows).fill(null)
279-
: this.getRows(table.schema, table.toArray().slice(0, this.remainingRows));
284+
const batchRows = Math.min(batch.numRows, this.remainingRows);
285+
let result: Array<any>;
286+
if (this.disableRowMaterialization) {
287+
result = new Array(batchRows).fill(null);
288+
} else if (this.rowMode === 'array') {
289+
result = this.getRowArrays(batch, batchRows);
290+
} else {
291+
const table = new Table(batch);
292+
result = this.getRows(table.schema, table.toArray().slice(0, this.remainingRows));
293+
}
280294

281295
// Reduce remaining rows count by a count of rows we just processed.
282296
// If the remaining count reached zero - we're done with current arrow
@@ -345,6 +359,29 @@ export default class ArrowResultConverter implements IResultsProvider<Array<any>
345359
});
346360
}
347361

362+
// Reads cells by column index, so same-named columns are all kept. Fields come from the
363+
// batch data type: `RecordBatch.schema` merges same-named fields into one type.
364+
private getRowArrays(batch: RecordBatch<TypeMap>, rowCount: number): Array<Array<any>> {
365+
const fields: Array<ArrowSchemaField> = batch.data.type.children;
366+
const vectors = this.schema.map((column, index) => batch.getChildAt(index));
367+
const rows: Array<Array<any>> = [];
368+
for (let i = 0; i < rowCount; i += 1) {
369+
const row: Array<any> = [];
370+
for (let j = 0; j < this.schema.length; j += 1) {
371+
const field = fields[j];
372+
const value = this.convertArrowTypes(
373+
vectors[j]?.get(i) ?? null,
374+
field?.type,
375+
field?.type.children || [],
376+
field,
377+
);
378+
row.push(this.convertThriftColumnValue(this.schema[j], value));
379+
}
380+
rows.push(row);
381+
}
382+
return rows;
383+
}
384+
348385
private convertArrowTypes(
349386
value: any,
350387
valueType: DataType | undefined,
@@ -489,4 +526,20 @@ export default class ArrowResultConverter implements IResultsProvider<Array<any>
489526

490527
return result;
491528
}
529+
530+
// Per-cell equivalent of `convertThriftTypes`, used by array rows. Kept separate so
531+
// the default object path stays as is.
532+
private convertThriftColumnValue(column: TColumnDesc, value: any): any {
533+
if (value === null) {
534+
return null;
535+
}
536+
const typeDescriptor = column.typeDesc.types[0]?.primitiveEntry;
537+
if (
538+
this.preserveBigNumericPrecision &&
539+
(typeDescriptor?.type === TTypeId.DECIMAL_TYPE || typeDescriptor?.type === TTypeId.BIGINT_TYPE)
540+
) {
541+
return value;
542+
}
543+
return convertThriftValue(typeDescriptor, value);
544+
}
492545
}

‎lib/result/JsonResultHandler.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { TGetResultSetMetadataResp, TRowSet, TColumn, TColumnDesc } from '../../thrift/TCLIService_types';
22
import IClientContext from '../contracts/IClientContext';
3+
import { RowMode } from '../contracts/IDBSQLSession';
34
import IResultsProvider, { ResultsProviderFetchNextOptions } from './IResultsProvider';
4-
import { getSchemaColumns, convertThriftValue, getColumnValue } from './utils';
5+
import { getSchemaColumns, convertThriftValue, getColumnValue, warnOnDuplicateColumnNames } from './utils';
56

67
export default class JsonResultHandler implements IResultsProvider<Array<any>> {
78
private readonly context: IClientContext;
@@ -10,14 +11,21 @@ export default class JsonResultHandler implements IResultsProvider<Array<any>> {
1011

1112
private readonly schema: Array<TColumnDesc>;
1213

14+
private readonly rowMode: RowMode;
15+
1316
constructor(
1417
context: IClientContext,
1518
source: IResultsProvider<TRowSet | undefined>,
1619
{ schema }: TGetResultSetMetadataResp,
20+
{ rowMode = 'object' }: { rowMode?: RowMode } = {},
1721
) {
1822
this.context = context;
1923
this.source = source;
2024
this.schema = getSchemaColumns(schema);
25+
this.rowMode = rowMode;
26+
if (rowMode === 'object') {
27+
warnOnDuplicateColumnNames(context, this.schema);
28+
}
2129
}
2230

2331
public async hasMore() {
@@ -35,7 +43,20 @@ export default class JsonResultHandler implements IResultsProvider<Array<any>> {
3543
}
3644

3745
const columns = data.columns || [];
38-
return this.getRows(columns, this.schema);
46+
return this.rowMode === 'array' ? this.getRowArrays(columns, this.schema) : this.getRows(columns, this.schema);
47+
}
48+
49+
private getRowArrays(columns: Array<TColumn>, descriptors: Array<TColumnDesc>): Array<Array<any>> {
50+
const rows: Array<Array<any>> = [];
51+
descriptors.forEach((descriptor, columnIndex) => {
52+
this.getSchemaValues(descriptor, columns[descriptor.position - 1]).forEach((value, i) => {
53+
if (!rows[i]) {
54+
rows[i] = [];
55+
}
56+
rows[i][columnIndex] = value;
57+
});
58+
});
59+
return rows;
3960
}
4061

4162
private getRows(columns: Array<TColumn>, descriptors: Array<TColumnDesc>): Array<any> {

‎lib/result/utils.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ import {
1818
} from 'apache-arrow';
1919
import { TTableSchema, TColumnDesc, TPrimitiveTypeEntry, TTypeId, TColumn } from '../../thrift/TCLIService_types';
2020
import HiveDriverError from '../errors/HiveDriverError';
21+
import IClientContext from '../contracts/IClientContext';
22+
import { LogLevel } from '../contracts/IDBSQLLogger';
2123

2224
export interface ArrowBatch {
2325
batches: Array<Buffer>;
@@ -32,6 +34,28 @@ export function getSchemaColumns(schema?: TTableSchema): Array<TColumnDesc> {
3234
return [...schema.columns].sort((c1, c2) => c1.position - c2.position);
3335
}
3436

37+
// Object rows are keyed by column name, so same-named columns overwrite each other.
38+
export function warnOnDuplicateColumnNames(context: IClientContext, columns: Array<TColumnDesc>): void {
39+
const seen = new Set<string>();
40+
const duplicates = new Set<string>();
41+
for (const { columnName } of columns) {
42+
if (seen.has(columnName)) {
43+
duplicates.add(columnName);
44+
}
45+
seen.add(columnName);
46+
}
47+
if (duplicates.size > 0) {
48+
const names = [...duplicates].map((name) => JSON.stringify(name)).join(', ');
49+
context
50+
.getLogger()
51+
.log(
52+
LogLevel.warn,
53+
`Result has duplicate column names (${names}); object rows keep only the last column with each name. ` +
54+
"Alias the columns or pass `rowMode: 'array'` to executeStatement to keep every column.",
55+
);
56+
}
57+
}
58+
3559
function isString(value: unknown): value is string {
3660
return typeof value === 'string' || value instanceof String;
3761
}

0 commit comments

Comments
 (0)