Skip to content
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased

- Preserve wide negative DECIMAL values exactly with `preserveBigNumericPrecision: true`, including nested arrays and structs, on both backends. The default number conversion is unchanged.
- 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.
- **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)
Expand Down
4 changes: 3 additions & 1 deletion lib/result/ArrowResultConverter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,10 @@ function formatDayTimeFromTotal(totalNanos: bigint): string {
* e.g. unscaled `1234567890` / scale `5` → `"12345.67890"`. Used by the
* precision-preserving path so high-precision DECIMALs survive the round-trip
* instead of being flattened to an IEEE-754 double.
* Arrow's `bigNumToBigInt` returns a decimal string for Decimal128 despite its `bigint` typing; normalize first.
*/
export function bigNumDecimalToString(unscaled: bigint, scale: number): string {
export function bigNumDecimalToString(value: bigint | string, scale: number): string {
const unscaled = BigInt(value);
if (scale <= 0) {
return unscaled.toString();
}
Expand Down
26 changes: 26 additions & 0 deletions tests/e2e/utils/rowMaterialization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ import { InternalConnectionOptions } from '../../../lib/contracts/InternalConnec
import config from './config';

const largeInteger = BigInt('9007199254740993');
const wideNegativeDecimal = '-123456789012345678.91';

export default function rowMaterializationTests(useKernel: boolean) {
describe(`Arrow row materialization (${useKernel ? 'kernel' : 'Thrift'})`, () => {
for (const rowMode of ['object', 'array'] as const) {
for (const useArrowNativeTypes of [false, true]) {
for (const preserveBigNumericPrecision of [false, true]) {
it(`preserves values (${rowMode}, native=${useArrowNativeTypes}, precision=${preserveBigNumericPrecision})`, async () => {
const nativeTypes = useKernel || useArrowNativeTypes;
const client = new DBSQLClient();
const base = client.getConfig();
client.getConfig = () => ({ ...base, useArrowNativeTypes });
Expand All @@ -33,6 +35,16 @@ export default function rowMaterializationTests(useKernel: boolean) {
IF(id = 1, NULL, CAST(300 AS SMALLINT)) AS small,
IF(id = 1, NULL, CAST(9007199254740993 AS BIGINT)) AS big,
IF(id = 1, NULL, CAST(1.25 AS DECIMAL(30,4))) AS dec,
IF(id = 1, NULL, CAST('${wideNegativeDecimal}' AS DECIMAL(38,2))) AS negative_dec,
${
nativeTypes
? `IF(id = 1, NULL, named_struct(
'amount', CAST('${wideNegativeDecimal}' AS NUMERIC(38,2)),
'items', array(CAST('${wideNegativeDecimal}' AS DEC(38,2)), NULL),
'values', map('negative', CAST('${wideNegativeDecimal}' AS DECIMAL(38,2)), 'missing', NULL)
)) AS nested_dec,`
: ''
}
IF(id = 1, NULL, CAST(1.25 AS FLOAT)) AS flt,
IF(id = 1, NULL, CAST(-2.5 AS DOUBLE)) AS dbl,
IF(id = 1, NULL, 'hello🌍') AS txt,
Expand All @@ -50,13 +62,27 @@ export default function rowMaterializationTests(useKernel: boolean) {
);
try {
const precise = preserveBigNumericPrecision;
const defaultNegativeDecimal = nativeTypes
? Number('-12345678901234567891') / 100
: Number(wideNegativeDecimal);
const negativeDecimal = precise ? wideNegativeDecimal : defaultNegativeDecimal;
const values = {
id: 0,
b: true,
tiny: -7,
small: 300,
big: precise ? largeInteger : 9007199254740992,
dec: precise ? '1.2500' : 1.25,
negative_dec: negativeDecimal,
...(nativeTypes
? {
nested_dec: {
amount: negativeDecimal,
items: [negativeDecimal, null],
values: { negative: negativeDecimal, missing: null },
},
}
: {}),
flt: 1.25,
dbl: -2.5,
txt: 'hello🌍',
Expand Down
20 changes: 15 additions & 5 deletions tests/unit/result/ArrowResultConverter.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { expect } from 'chai';
import fs from 'fs';
import path from 'path';
import { Table, tableFromArrays, tableToIPC, RecordBatch, TypeMap } from 'apache-arrow';
import { Table, tableFromArrays, tableToIPC, RecordBatch, TypeMap, Decimal, vectorFromArray, util } from 'apache-arrow';
import ArrowResultConverter, { bigNumDecimalToString } from '../../../lib/result/ArrowResultConverter';
import { ArrowBatch } from '../../../lib/result/utils';
import ResultsProviderStub from '../.stubs/ResultsProviderStub';
Expand Down Expand Up @@ -293,10 +293,20 @@ describe('ArrowResultConverter', () => {
});

it('formats unscaled decimals to exact strings (bigNumDecimalToString)', () => {
expect(bigNumDecimalToString(BigInt('1234567890'), 5)).to.equal('12345.67890'); // trailing zero kept
const unscaled = ['1234567890', '-1234567890123456789', '5', '-5', '12345'];
const values = vectorFromArray(
unscaled.map((value) => {
const unsigned = BigInt.asUintN(128, BigInt(value));
return Uint32Array.from([0, 32, 64, 96], (shift) => Number((unsigned >> BigInt(shift)) & BigInt('4294967295')));
}),
new Decimal(0, 38, 128),
);
const fromArrow = (index: number) => util.bigNumToBigInt(util.BN.decimal(values.get(index)!));
expect(bigNumDecimalToString(fromArrow(0), 5)).to.equal('12345.67890');
expect(bigNumDecimalToString(fromArrow(1), 4)).to.equal('-123456789012345.6789');
expect(bigNumDecimalToString(fromArrow(2), 2)).to.equal('0.05');
expect(bigNumDecimalToString(fromArrow(3), 2)).to.equal('-0.05');
expect(bigNumDecimalToString(fromArrow(4), 0)).to.equal('12345');
expect(bigNumDecimalToString(BigInt('-1234567890123456789'), 4)).to.equal('-123456789012345.6789');
expect(bigNumDecimalToString(BigInt('5'), 2)).to.equal('0.05'); // leading zero synthesized
expect(bigNumDecimalToString(BigInt('-5'), 2)).to.equal('-0.05');
expect(bigNumDecimalToString(BigInt('12345'), 0)).to.equal('12345'); // scale 0 → integer string
});
});
67 changes: 46 additions & 21 deletions tests/unit/result/ArrowRowMaterialization.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,22 +142,47 @@ describe('Arrow row materialization', () => {
thriftType: TTypeId.DECIMAL_TYPE,
values: unscaled.map((value) => (value === null ? null : decimal(value))),
expected: unscaled.map((value) => (value === null ? null : Number(value) / 10 ** scale)),
precise:
scale < 0
? undefined
: unscaled.map((value) => {
if (value === null) {
return null;
}
const integer = BigInt(value);
if (scale === 0) {
return integer.toString();
}
const negative = integer < BigInt(0);
const magnitude = negative ? -integer : integer;
const divisor = BigInt(10) ** BigInt(scale);
const fraction = (magnitude % divisor).toString().padStart(scale, '0');
return `${negative ? '-' : ''}${magnitude / divisor}.${fraction}`;
}),
}));
const converter = converterFor(columns, rowMode);
const expected = unscaled.map((value, rowIndex) =>
rowMode === 'array'
? columns.map((column) => column.expected[rowIndex])
: Object.fromEntries(columns.map((column) => [column.field.name, column.expected[rowIndex]])),
);
deepStrictEqual(await converter.fetchNext({ limit: 100 }), expected);
const batch = arrow.tableFromIPC(ipc(columns)).batches[0];
deepStrictEqual((converter as any).getRows(batch.slice(3, 15), 8), expected.slice(3, 11));
const legacyRows = (converter as any).getObjectRows(batch.schema, batch.toArray());
deepStrictEqual(
rowMode === 'array'
? legacyRows.map((row: any) => columns.map((column) => row[column.field.name]))
: legacyRows,
expected,
await Promise.all(
[false, true].map(async (preserveBigNumericPrecision) => {
const modeColumns = columns.filter((column) => !preserveBigNumericPrecision || column.field.type.scale >= 0);
const converter = converterFor(modeColumns, rowMode, preserveBigNumericPrecision);
const expected = unscaled.map((value, rowIndex) => {
const values = modeColumns.map((column) =>
preserveBigNumericPrecision ? column.precise![rowIndex] : column.expected[rowIndex],
);
return rowMode === 'array'
? values
: Object.fromEntries(modeColumns.map((column, index) => [column.field.name, values[index]]));
});
deepStrictEqual(await converter.fetchNext({ limit: 100 }), expected);
const batch = arrow.tableFromIPC(ipc(modeColumns)).batches[0];
deepStrictEqual((converter as any).getRows(batch.slice(3, 15), 8), expected.slice(3, 11));
const legacyRows = (converter as any).getObjectRows(batch.schema, batch.toArray());
deepStrictEqual(
rowMode === 'array'
? legacyRows.map((row: any) => modeColumns.map((column) => row[column.field.name]))
: legacyRows,
expected,
);
}),
);
});

Expand Down Expand Up @@ -247,9 +272,9 @@ describe('Arrow row materialization', () => {
{
field: new arrow.Field('decimal', new arrow.Decimal(4, 38, 128)),
thriftType: TTypeId.DECIMAL_TYPE,
values: [decimal('90071992547409931234'), null, decimal('-12500')],
expected: [Number(BigInt('90071992547409931234')) / 10000, null, -1.25],
precise: ['9007199254740993.1234', null, '-1.2500'],
values: [decimal('90071992547409931234'), null, decimal('-12345678901234567891')],
expected: [Number(BigInt('90071992547409931234')) / 10000, null, -1234567890123456.8],
precise: ['9007199254740993.1234', null, '-1234567890123456.7891'],
},
{
field: new arrow.Field('text', new arrow.Utf8()),
Expand Down Expand Up @@ -472,10 +497,10 @@ describe('Arrow row materialization', () => {
name: 'DECIMAL',
type: () => new arrow.Decimal(4, 38, 128),
thriftType: TTypeId.DECIMAL_TYPE,
values: [decimal('90071992547409931234'), decimal('-12500'), decimal('0')],
expected: ['9007199254740993.1234', '-1.2500', '0.0000'],
values: [decimal('90071992547409931234'), decimal('-12345678901234567891'), decimal('0')],
expected: ['9007199254740993.1234', '-1234567890123456.7891', '0.0000'],
// Dictionary decimals retain the legacy unscaled string representation.
dictionaryExpected: ['90071992547409931234', '-12500', '0'],
dictionaryExpected: ['90071992547409931234', '-12345678901234567891', '0'],
},
]) {
for (const dictionaryEncoded of [false, true]) {
Expand Down
Loading