diff --git a/CHANGELOG.md b/CHANGELOG.md index 3eaac70f..d2a9bfc0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/lib/result/ArrowResultConverter.ts b/lib/result/ArrowResultConverter.ts index 441c495f..52911d5b 100644 --- a/lib/result/ArrowResultConverter.ts +++ b/lib/result/ArrowResultConverter.ts @@ -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(); } diff --git a/tests/e2e/utils/rowMaterialization.ts b/tests/e2e/utils/rowMaterialization.ts index 9c862238..cc6799a1 100644 --- a/tests/e2e/utils/rowMaterialization.ts +++ b/tests/e2e/utils/rowMaterialization.ts @@ -5,6 +5,7 @@ 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'})`, () => { @@ -12,6 +13,7 @@ export default function rowMaterializationTests(useKernel: boolean) { 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 }); @@ -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, @@ -50,6 +62,10 @@ 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, @@ -57,6 +73,16 @@ export default function rowMaterializationTests(useKernel: boolean) { 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🌍', diff --git a/tests/unit/result/ArrowResultConverter.test.ts b/tests/unit/result/ArrowResultConverter.test.ts index 363b3cc8..c4561635 100644 --- a/tests/unit/result/ArrowResultConverter.test.ts +++ b/tests/unit/result/ArrowResultConverter.test.ts @@ -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'; @@ -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 }); }); diff --git a/tests/unit/result/ArrowRowMaterialization.test.ts b/tests/unit/result/ArrowRowMaterialization.test.ts index 7afb6e89..844f6a9e 100644 --- a/tests/unit/result/ArrowRowMaterialization.test.ts +++ b/tests/unit/result/ArrowRowMaterialization.test.ts @@ -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, + ); + }), ); }); @@ -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()), @@ -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]) {