Skip to content

Commit 2c4d50a

Browse files
vuanhphungIsaac
andauthored
Preserve exact wide negative DECIMAL values (#658)
* Preserve exact wide negative DECIMAL values Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com> * Cover high-scale precise decimals and explain Arrow normalization Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com> * Consolidate wide-negative DECIMAL regression fixtures Exclude negative scales from precision-exact assertions and extend shared unit and live fixtures instead of duplicating conversion and session setup. Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> 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 7d34172 commit 2c4d50a

5 files changed

Lines changed: 91 additions & 27 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
## Unreleased
44

5+
- Preserve wide negative DECIMAL values exactly with `preserveBigNumericPrecision: true`, including nested arrays and structs, on both backends. The default number conversion is unchanged.
56
- 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`.
67
- Release completed Thrift CloudFetch body-reader listeners so idle connections do not retain downloaded result buffers.
78
- **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)

‎lib/result/ArrowResultConverter.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,8 +179,10 @@ function formatDayTimeFromTotal(totalNanos: bigint): string {
179179
* e.g. unscaled `1234567890` / scale `5` → `"12345.67890"`. Used by the
180180
* precision-preserving path so high-precision DECIMALs survive the round-trip
181181
* instead of being flattened to an IEEE-754 double.
182+
* Arrow's `bigNumToBigInt` returns a decimal string for Decimal128 despite its `bigint` typing; normalize first.
182183
*/
183-
export function bigNumDecimalToString(unscaled: bigint, scale: number): string {
184+
export function bigNumDecimalToString(value: bigint | string, scale: number): string {
185+
const unscaled = BigInt(value);
184186
if (scale <= 0) {
185187
return unscaled.toString();
186188
}

‎tests/e2e/utils/rowMaterialization.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,15 @@ import { InternalConnectionOptions } from '../../../lib/contracts/InternalConnec
55
import config from './config';
66

77
const largeInteger = BigInt('9007199254740993');
8+
const wideNegativeDecimal = '-123456789012345678.91';
89

910
export default function rowMaterializationTests(useKernel: boolean) {
1011
describe(`Arrow row materialization (${useKernel ? 'kernel' : 'Thrift'})`, () => {
1112
for (const rowMode of ['object', 'array'] as const) {
1213
for (const useArrowNativeTypes of [false, true]) {
1314
for (const preserveBigNumericPrecision of [false, true]) {
1415
it(`preserves values (${rowMode}, native=${useArrowNativeTypes}, precision=${preserveBigNumericPrecision})`, async () => {
16+
const nativeTypes = useKernel || useArrowNativeTypes;
1517
const client = new DBSQLClient();
1618
const base = client.getConfig();
1719
client.getConfig = () => ({ ...base, useArrowNativeTypes });
@@ -33,6 +35,16 @@ export default function rowMaterializationTests(useKernel: boolean) {
3335
IF(id = 1, NULL, CAST(300 AS SMALLINT)) AS small,
3436
IF(id = 1, NULL, CAST(9007199254740993 AS BIGINT)) AS big,
3537
IF(id = 1, NULL, CAST(1.25 AS DECIMAL(30,4))) AS dec,
38+
IF(id = 1, NULL, CAST('${wideNegativeDecimal}' AS DECIMAL(38,2))) AS negative_dec,
39+
${
40+
nativeTypes
41+
? `IF(id = 1, NULL, named_struct(
42+
'amount', CAST('${wideNegativeDecimal}' AS NUMERIC(38,2)),
43+
'items', array(CAST('${wideNegativeDecimal}' AS DEC(38,2)), NULL),
44+
'values', map('negative', CAST('${wideNegativeDecimal}' AS DECIMAL(38,2)), 'missing', NULL)
45+
)) AS nested_dec,`
46+
: ''
47+
}
3648
IF(id = 1, NULL, CAST(1.25 AS FLOAT)) AS flt,
3749
IF(id = 1, NULL, CAST(-2.5 AS DOUBLE)) AS dbl,
3850
IF(id = 1, NULL, 'hello🌍') AS txt,
@@ -50,13 +62,27 @@ export default function rowMaterializationTests(useKernel: boolean) {
5062
);
5163
try {
5264
const precise = preserveBigNumericPrecision;
65+
const defaultNegativeDecimal = nativeTypes
66+
? Number('-12345678901234567891') / 100
67+
: Number(wideNegativeDecimal);
68+
const negativeDecimal = precise ? wideNegativeDecimal : defaultNegativeDecimal;
5369
const values = {
5470
id: 0,
5571
b: true,
5672
tiny: -7,
5773
small: 300,
5874
big: precise ? largeInteger : 9007199254740992,
5975
dec: precise ? '1.2500' : 1.25,
76+
negative_dec: negativeDecimal,
77+
...(nativeTypes
78+
? {
79+
nested_dec: {
80+
amount: negativeDecimal,
81+
items: [negativeDecimal, null],
82+
values: { negative: negativeDecimal, missing: null },
83+
},
84+
}
85+
: {}),
6086
flt: 1.25,
6187
dbl: -2.5,
6288
txt: 'hello🌍',

‎tests/unit/result/ArrowResultConverter.test.ts‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { expect } from 'chai';
22
import fs from 'fs';
33
import path from 'path';
4-
import { Table, tableFromArrays, tableToIPC, RecordBatch, TypeMap } from 'apache-arrow';
4+
import { Table, tableFromArrays, tableToIPC, RecordBatch, TypeMap, Decimal, vectorFromArray, util } from 'apache-arrow';
55
import ArrowResultConverter, { bigNumDecimalToString } from '../../../lib/result/ArrowResultConverter';
66
import { ArrowBatch } from '../../../lib/result/utils';
77
import ResultsProviderStub from '../.stubs/ResultsProviderStub';
@@ -293,10 +293,20 @@ describe('ArrowResultConverter', () => {
293293
});
294294

295295
it('formats unscaled decimals to exact strings (bigNumDecimalToString)', () => {
296-
expect(bigNumDecimalToString(BigInt('1234567890'), 5)).to.equal('12345.67890'); // trailing zero kept
296+
const unscaled = ['1234567890', '-1234567890123456789', '5', '-5', '12345'];
297+
const values = vectorFromArray(
298+
unscaled.map((value) => {
299+
const unsigned = BigInt.asUintN(128, BigInt(value));
300+
return Uint32Array.from([0, 32, 64, 96], (shift) => Number((unsigned >> BigInt(shift)) & BigInt('4294967295')));
301+
}),
302+
new Decimal(0, 38, 128),
303+
);
304+
const fromArrow = (index: number) => util.bigNumToBigInt(util.BN.decimal(values.get(index)!));
305+
expect(bigNumDecimalToString(fromArrow(0), 5)).to.equal('12345.67890');
306+
expect(bigNumDecimalToString(fromArrow(1), 4)).to.equal('-123456789012345.6789');
307+
expect(bigNumDecimalToString(fromArrow(2), 2)).to.equal('0.05');
308+
expect(bigNumDecimalToString(fromArrow(3), 2)).to.equal('-0.05');
309+
expect(bigNumDecimalToString(fromArrow(4), 0)).to.equal('12345');
297310
expect(bigNumDecimalToString(BigInt('-1234567890123456789'), 4)).to.equal('-123456789012345.6789');
298-
expect(bigNumDecimalToString(BigInt('5'), 2)).to.equal('0.05'); // leading zero synthesized
299-
expect(bigNumDecimalToString(BigInt('-5'), 2)).to.equal('-0.05');
300-
expect(bigNumDecimalToString(BigInt('12345'), 0)).to.equal('12345'); // scale 0 → integer string
301311
});
302312
});

‎tests/unit/result/ArrowRowMaterialization.test.ts‎

Lines changed: 46 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -142,22 +142,47 @@ describe('Arrow row materialization', () => {
142142
thriftType: TTypeId.DECIMAL_TYPE,
143143
values: unscaled.map((value) => (value === null ? null : decimal(value))),
144144
expected: unscaled.map((value) => (value === null ? null : Number(value) / 10 ** scale)),
145+
precise:
146+
scale < 0
147+
? undefined
148+
: unscaled.map((value) => {
149+
if (value === null) {
150+
return null;
151+
}
152+
const integer = BigInt(value);
153+
if (scale === 0) {
154+
return integer.toString();
155+
}
156+
const negative = integer < BigInt(0);
157+
const magnitude = negative ? -integer : integer;
158+
const divisor = BigInt(10) ** BigInt(scale);
159+
const fraction = (magnitude % divisor).toString().padStart(scale, '0');
160+
return `${negative ? '-' : ''}${magnitude / divisor}.${fraction}`;
161+
}),
145162
}));
146-
const converter = converterFor(columns, rowMode);
147-
const expected = unscaled.map((value, rowIndex) =>
148-
rowMode === 'array'
149-
? columns.map((column) => column.expected[rowIndex])
150-
: Object.fromEntries(columns.map((column) => [column.field.name, column.expected[rowIndex]])),
151-
);
152-
deepStrictEqual(await converter.fetchNext({ limit: 100 }), expected);
153-
const batch = arrow.tableFromIPC(ipc(columns)).batches[0];
154-
deepStrictEqual((converter as any).getRows(batch.slice(3, 15), 8), expected.slice(3, 11));
155-
const legacyRows = (converter as any).getObjectRows(batch.schema, batch.toArray());
156-
deepStrictEqual(
157-
rowMode === 'array'
158-
? legacyRows.map((row: any) => columns.map((column) => row[column.field.name]))
159-
: legacyRows,
160-
expected,
163+
await Promise.all(
164+
[false, true].map(async (preserveBigNumericPrecision) => {
165+
const modeColumns = columns.filter((column) => !preserveBigNumericPrecision || column.field.type.scale >= 0);
166+
const converter = converterFor(modeColumns, rowMode, preserveBigNumericPrecision);
167+
const expected = unscaled.map((value, rowIndex) => {
168+
const values = modeColumns.map((column) =>
169+
preserveBigNumericPrecision ? column.precise![rowIndex] : column.expected[rowIndex],
170+
);
171+
return rowMode === 'array'
172+
? values
173+
: Object.fromEntries(modeColumns.map((column, index) => [column.field.name, values[index]]));
174+
});
175+
deepStrictEqual(await converter.fetchNext({ limit: 100 }), expected);
176+
const batch = arrow.tableFromIPC(ipc(modeColumns)).batches[0];
177+
deepStrictEqual((converter as any).getRows(batch.slice(3, 15), 8), expected.slice(3, 11));
178+
const legacyRows = (converter as any).getObjectRows(batch.schema, batch.toArray());
179+
deepStrictEqual(
180+
rowMode === 'array'
181+
? legacyRows.map((row: any) => modeColumns.map((column) => row[column.field.name]))
182+
: legacyRows,
183+
expected,
184+
);
185+
}),
161186
);
162187
});
163188

@@ -247,9 +272,9 @@ describe('Arrow row materialization', () => {
247272
{
248273
field: new arrow.Field('decimal', new arrow.Decimal(4, 38, 128)),
249274
thriftType: TTypeId.DECIMAL_TYPE,
250-
values: [decimal('90071992547409931234'), null, decimal('-12500')],
251-
expected: [Number(BigInt('90071992547409931234')) / 10000, null, -1.25],
252-
precise: ['9007199254740993.1234', null, '-1.2500'],
275+
values: [decimal('90071992547409931234'), null, decimal('-12345678901234567891')],
276+
expected: [Number(BigInt('90071992547409931234')) / 10000, null, -1234567890123456.8],
277+
precise: ['9007199254740993.1234', null, '-1234567890123456.7891'],
253278
},
254279
{
255280
field: new arrow.Field('text', new arrow.Utf8()),
@@ -472,10 +497,10 @@ describe('Arrow row materialization', () => {
472497
name: 'DECIMAL',
473498
type: () => new arrow.Decimal(4, 38, 128),
474499
thriftType: TTypeId.DECIMAL_TYPE,
475-
values: [decimal('90071992547409931234'), decimal('-12500'), decimal('0')],
476-
expected: ['9007199254740993.1234', '-1.2500', '0.0000'],
500+
values: [decimal('90071992547409931234'), decimal('-12345678901234567891'), decimal('0')],
501+
expected: ['9007199254740993.1234', '-1234567890123456.7891', '0.0000'],
477502
// Dictionary decimals retain the legacy unscaled string representation.
478-
dictionaryExpected: ['90071992547409931234', '-12500', '0'],
503+
dictionaryExpected: ['90071992547409931234', '-12345678901234567891', '0'],
479504
},
480505
]) {
481506
for (const dictionaryEncoded of [false, true]) {

0 commit comments

Comments
 (0)