From 8b3e81b82ee0c67c6e8feb157579802b925e8af5 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Wed, 2 Dec 2026 19:47:15 +0000 Subject: [PATCH 1/5] Preserve exact DECIMAL map keys on both backends Format Decimal128 keys at their declared scale before Arrow MapRow coerces them to strings, regardless of numeric-value precision mode. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- CHANGELOG.md | 2 + lib/result/ArrowResultConverter.ts | 8 ++- tests/e2e/decimal-map-keys.test.ts | 50 +++++++++++++++++ .../result/ArrowRowMaterialization.test.ts | 54 +++++++++++++++++++ 4 files changed, 112 insertions(+), 2 deletions(-) create mode 100644 tests/e2e/decimal-map-keys.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b630444..34184333 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- **Behavior change:** DECIMAL map keys now retain their exact magnitude and declared scale on both backends, regardless of `preserveBigNumericPrecision`. Look up a DECIMAL(10,2) key of 1.50 as `"1.50"`, not the previously incorrect `"150"`. + - 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..78a915a6 100644 --- a/lib/result/ArrowResultConverter.ts +++ b/lib/result/ArrowResultConverter.ts @@ -482,8 +482,12 @@ export default class ArrowResultConverter implements IResultsProvider return result; } if (value instanceof MapRow) { - const result = value.toJSON(); - // Map type consists of its key and value types. We need only value type here, key will be cast to string anyway + const keyType = fieldsMap.entries?.type.children.find((item) => item.name === 'key')?.type; + const result = DataType.isDecimal(keyType) + ? Object.fromEntries( + Array.from(value, ([key, item]) => [bigNumDecimalToString(bigNumToBigInt(key), keyType.scale), item]), + ) + : value.toJSON(); const valueField = fieldsMap.entries?.type.children.find((item) => item.name === 'value'); for (const key of Object.keys(result)) { result[key] = this.convertArrowTypes( diff --git a/tests/e2e/decimal-map-keys.test.ts b/tests/e2e/decimal-map-keys.test.ts new file mode 100644 index 00000000..48726244 --- /dev/null +++ b/tests/e2e/decimal-map-keys.test.ts @@ -0,0 +1,50 @@ +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'; + +function decimalMapKeysTests(useKernel: boolean) { + describe(`DECIMAL map keys (${useKernel ? 'kernel' : 'Thrift'})`, () => { + for (const preserveBigNumericPrecision of [false, true]) { + it(`preserves exact keys (precision=${preserveBigNumericPrecision})`, async () => { + const client = new DBSQLClient(); + try { + await client.connect({ + host: config.host, + path: config.path, + token: config.token, + useKernel, + preserveBigNumericPrecision, + } as ConnectionOptions & InternalConnectionOptions); + const session = await client.openSession(); + try { + const operation = await session.executeStatement(` + SELECT map(CAST(1.50 AS DECIMAL(10,2)), 'positive', CAST(-0.05 AS DECIMAL(10,2)), NULL) AS amounts, + array(map(CAST(0.0000001 AS DECIMAL(20,7)), 'tiny')) AS nested, + map(CAST('999999999999999999999999999999999999.99' AS DECIMAL(38,2)), 'wide') AS wide + `); + try { + expect(await operation.fetchAll()).to.deep.equal([ + { + amounts: { '1.50': 'positive', '-0.05': null }, + nested: [{ '0.0000001': 'tiny' }], + wide: { '999999999999999999999999999999999999.99': 'wide' }, + }, + ]); + } finally { + await operation.close(); + } + } finally { + await session.close(); + } + } finally { + await client.close(); + } + }); + } + }); +} + +decimalMapKeysTests(false); +decimalMapKeysTests(true); diff --git a/tests/unit/result/ArrowRowMaterialization.test.ts b/tests/unit/result/ArrowRowMaterialization.test.ts index 7afb6e89..55322743 100644 --- a/tests/unit/result/ArrowRowMaterialization.test.ts +++ b/tests/unit/result/ArrowRowMaterialization.test.ts @@ -215,6 +215,60 @@ describe('Arrow row materialization', () => { ); }); + for (const scale of [2, 7]) { + for (const preservePrecision of [false, true]) { + it(`preserves Decimal128 map keys (${rowMode}, scale=${scale}, precision=${preservePrecision})`, async () => { + const mapType = new arrow.Map_( + new arrow.Field( + 'entries', + new arrow.Struct<{ key: arrow.Decimal; value: arrow.Utf8 }>([ + new arrow.Field('key', new arrow.Decimal(scale, 38, 128), false), + new arrow.Field('value', new arrow.Utf8()), + ]), + ), + ); + const keys = ['150', '-5', '1', '0', '99999999999999999999999999999999999999']; + const expectedKeys = + scale === 2 + ? ['1.50', '-0.05', '0.01', '0.00', '999999999999999999999999999999999999.99'] + : ['0.0000150', '-0.0000005', '0.0000001', '0.0000000', '9999999999999999999999999999999.9999999']; + const map = new Map(keys.map((key, index) => [decimal(key), index === 3 ? null : `value${index}`])); + const expectedMap = Object.fromEntries( + expectedKeys.map((key, index) => [key, index === 3 ? null : `value${index}`]), + ); + const columns: Column[] = [ + { + field: new arrow.Field('map', mapType), + thriftType: TTypeId.MAP_TYPE, + values: [map, new Map(), null], + expected: [expectedMap, {}, null], + }, + { + field: new arrow.Field('nested', new arrow.List(new arrow.Field('element', mapType))), + thriftType: TTypeId.ARRAY_TYPE, + values: [[map], [], null], + expected: [[expectedMap], [], null], + }, + ]; + const expected = [0, 1, 2].map((rowIndex) => + rowMode === 'array' + ? columns.map((column) => column.expected[rowIndex]) + : Object.fromEntries(columns.map((column) => [column.field.name, column.expected[rowIndex]])), + ); + const converter = converterFor(columns, rowMode, preservePrecision); + deepStrictEqual(await converter.fetchNext({ limit: 100 }), expected); + const batch = arrow.tableFromIPC(ipc(columns)).batches[0]; + 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, + ); + }); + } + } + for (const preservePrecision of [false, true]) { it(`preserves scalar values, types and nulls (${rowMode}, precision=${preservePrecision})`, async () => { const timestamp = new Date('2026-01-02T03:04:05.000Z'); From 812e9c5936b54d31b4a2dd13a74fef76593bba78 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Wed, 2 Dec 2026 20:30:14 +0000 Subject: [PATCH 2/5] Normalize wide negative DECIMAL map keys before formatting Convert Arrow 13's string-valued Decimal128 result to bigint only at the map-key call site. Cover wide negative keys and adjacent entries without changing decimal value conversion. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- CHANGELOG.md | 2 +- lib/result/ArrowResultConverter.ts | 5 +- tests/e2e/decimal-map-keys.test.ts | 13 +++- .../result/ArrowRowMaterialization.test.ts | 74 ++++++++++++++++++- 4 files changed, 87 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 34184333..14d74980 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- **Behavior change:** DECIMAL map keys now retain their exact magnitude and declared scale on both backends, regardless of `preserveBigNumericPrecision`. Look up a DECIMAL(10,2) key of 1.50 as `"1.50"`, not the previously incorrect `"150"`. +- **Behavior change:** Arrow DECIMAL map keys now use exact plain fixed-point strings at the declared scale, including wide negative keys, on both backends and with either `preserveBigNumericPrecision` setting. Look up a DECIMAL(10,2) key of 1.50 as `"1.50"`, not the previously incorrect `"150"`. DECIMAL value conversion and non-Arrow Thrift modes are 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. diff --git a/lib/result/ArrowResultConverter.ts b/lib/result/ArrowResultConverter.ts index 78a915a6..ec30b6e2 100644 --- a/lib/result/ArrowResultConverter.ts +++ b/lib/result/ArrowResultConverter.ts @@ -485,7 +485,10 @@ export default class ArrowResultConverter implements IResultsProvider const keyType = fieldsMap.entries?.type.children.find((item) => item.name === 'key')?.type; const result = DataType.isDecimal(keyType) ? Object.fromEntries( - Array.from(value, ([key, item]) => [bigNumDecimalToString(bigNumToBigInt(key), keyType.scale), item]), + Array.from(value, ([key, item]) => [ + bigNumDecimalToString(BigInt(bigNumToBigInt(key)), keyType.scale), + item, + ]), ) : value.toJSON(); const valueField = fieldsMap.entries?.type.children.find((item) => item.name === 'value'); diff --git a/tests/e2e/decimal-map-keys.test.ts b/tests/e2e/decimal-map-keys.test.ts index 48726244..d7a5474c 100644 --- a/tests/e2e/decimal-map-keys.test.ts +++ b/tests/e2e/decimal-map-keys.test.ts @@ -22,14 +22,23 @@ function decimalMapKeysTests(useKernel: boolean) { const operation = await session.executeStatement(` SELECT map(CAST(1.50 AS DECIMAL(10,2)), 'positive', CAST(-0.05 AS DECIMAL(10,2)), NULL) AS amounts, array(map(CAST(0.0000001 AS DECIMAL(20,7)), 'tiny')) AS nested, - map(CAST('999999999999999999999999999999999999.99' AS DECIMAL(38,2)), 'wide') AS wide + map(CAST('999999999999999999999999999999999999.99' AS DECIMAL(38,2)), 'wide', + CAST('-999999999999999999999999999999999999.99' AS DECIMAL(38,2)), 'negative') AS wide, + map(CAST('-90071992547409.93' AS DECIMAL(38,2)), 'unsafe') AS negative_unsafe, + map(CAST('-123456789012345678.90' AS DECIMAL(38,2)), 'first', + CAST('-123456789012345678.91' AS DECIMAL(38,2)), 'second') AS negative_pair `); try { expect(await operation.fetchAll()).to.deep.equal([ { amounts: { '1.50': 'positive', '-0.05': null }, nested: [{ '0.0000001': 'tiny' }], - wide: { '999999999999999999999999999999999999.99': 'wide' }, + wide: { + '999999999999999999999999999999999999.99': 'wide', + '-999999999999999999999999999999999999.99': 'negative', + }, + negative_unsafe: { '-90071992547409.93': 'unsafe' }, + negative_pair: { '-123456789012345678.90': 'first', '-123456789012345678.91': 'second' }, }, ]); } finally { diff --git a/tests/unit/result/ArrowRowMaterialization.test.ts b/tests/unit/result/ArrowRowMaterialization.test.ts index 55322743..c9e9fd42 100644 --- a/tests/unit/result/ArrowRowMaterialization.test.ts +++ b/tests/unit/result/ArrowRowMaterialization.test.ts @@ -227,11 +227,41 @@ describe('Arrow row materialization', () => { ]), ), ); - const keys = ['150', '-5', '1', '0', '99999999999999999999999999999999999999']; + const keys = [ + '150', + '-5', + '1', + '0', + '99999999999999999999999999999999999999', + '-99999999999999999999999999999999999999', + '-9007199254740993', + '-12345678901234567890', + '-12345678901234567891', + ]; const expectedKeys = scale === 2 - ? ['1.50', '-0.05', '0.01', '0.00', '999999999999999999999999999999999999.99'] - : ['0.0000150', '-0.0000005', '0.0000001', '0.0000000', '9999999999999999999999999999999.9999999']; + ? [ + '1.50', + '-0.05', + '0.01', + '0.00', + '999999999999999999999999999999999999.99', + '-999999999999999999999999999999999999.99', + '-90071992547409.93', + '-123456789012345678.90', + '-123456789012345678.91', + ] + : [ + '0.0000150', + '-0.0000005', + '0.0000001', + '0.0000000', + '9999999999999999999999999999999.9999999', + '-9999999999999999999999999999999.9999999', + '-900719925.4740993', + '-1234567890123.4567890', + '-1234567890123.4567891', + ]; const map = new Map(keys.map((key, index) => [decimal(key), index === 3 ? null : `value${index}`])); const expectedMap = Object.fromEntries( expectedKeys.map((key, index) => [key, index === 3 ? null : `value${index}`]), @@ -266,6 +296,44 @@ describe('Arrow row materialization', () => { expected, ); }); + + for (const [unscaledKeys, expectedKeys] of [ + [ + ['-99999999999999999999999999999999999999'], + [scale === 2 ? '-999999999999999999999999999999999999.99' : '-9999999999999999999999999999999.9999999'], + ], + [['-9007199254740993'], [scale === 2 ? '-90071992547409.93' : '-900719925.4740993']], + [ + ['-12345678901234567890', '-12345678901234567891'], + scale === 2 + ? ['-123456789012345678.90', '-123456789012345678.91'] + : ['-1234567890123.4567890', '-1234567890123.4567891'], + ], + ]) { + it(`keeps negative Decimal128 map entries (${rowMode}, scale=${scale}, precision=${preservePrecision}, keys=${unscaledKeys})`, async () => { + const mapType = new arrow.Map_( + new arrow.Field( + 'entries', + new arrow.Struct<{ key: arrow.Decimal; value: arrow.Utf8 }>([ + new arrow.Field('key', new arrow.Decimal(scale, 38, 128), false), + new arrow.Field('value', new arrow.Utf8()), + ]), + ), + ); + const columns: Column[] = [ + { + field: new arrow.Field('map', mapType), + thriftType: TTypeId.MAP_TYPE, + values: [new Map(unscaledKeys.map((key, index) => [decimal(key), `value${index}`]))], + expected: [Object.fromEntries(expectedKeys.map((key, index) => [key, `value${index}`]))], + }, + ]; + const [row] = await converterFor(columns, rowMode, preservePrecision).fetchNext({ limit: 100 }); + const result = rowMode === 'array' ? row[0] : row.map; + expect(Object.keys(result)).to.have.length(unscaledKeys.length); + deepStrictEqual(result, columns[0].expected[0]); + }); + } } } From c978f6a3224a2f4b2dc8be1f308f9fc4912d122d Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Wed, 2 Dec 2026 21:02:53 +0000 Subject: [PATCH 3/5] Document DECIMAL map key enumeration order Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 14d74980..f0f56efe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- **Behavior change:** Arrow DECIMAL map keys now use exact plain fixed-point strings at the declared scale, including wide negative keys, on both backends and with either `preserveBigNumericPrecision` setting. Look up a DECIMAL(10,2) key of 1.50 as `"1.50"`, not the previously incorrect `"150"`. DECIMAL value conversion and non-Arrow Thrift modes are unchanged. +- **Behavior change:** Arrow DECIMAL map keys now use exact plain fixed-point strings at the declared scale, including wide negative keys, on both backends and with either `preserveBigNumericPrecision` setting; keys with a positive scale now enumerate in server order. Look up a DECIMAL(10,2) key of 1.50 as `"1.50"`, not the previously incorrect `"150"`. DECIMAL value conversion and non-Arrow Thrift modes are 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. From b556574b148ba3b593f5a70d14b01a665b8f256d Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Wed, 2 Dec 2026 21:05:55 +0000 Subject: [PATCH 4/5] Match Unreleased changelog list spacing Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f0f56efe..1d040fde 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,6 @@ ## Unreleased - **Behavior change:** Arrow DECIMAL map keys now use exact plain fixed-point strings at the declared scale, including wide negative keys, on both backends and with either `preserveBigNumericPrecision` setting; keys with a positive scale now enumerate in server order. Look up a DECIMAL(10,2) key of 1.50 as `"1.50"`, not the previously incorrect `"150"`. DECIMAL value conversion and non-Arrow Thrift modes are 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) From 839a203a256f685cb2d41c11249c548890669ad2 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 3 Dec 2026 05:09:36 +0000 Subject: [PATCH 5/5] Optimize DECIMAL map keys and cover ordering on both backends Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- lib/result/ArrowResultConverter.ts | 18 ++++- tests/e2e/decimal-map-keys.test.ts | 58 +------------ tests/e2e/kernel/decimal-map-keys-e2e.test.ts | 3 + tests/e2e/utils/decimalMapKeys.ts | 56 +++++++++++++ .../result/ArrowRowMaterialization.test.ts | 81 ++++++++++++++++++- 5 files changed, 153 insertions(+), 63 deletions(-) create mode 100644 tests/e2e/kernel/decimal-map-keys-e2e.test.ts create mode 100644 tests/e2e/utils/decimalMapKeys.ts diff --git a/lib/result/ArrowResultConverter.ts b/lib/result/ArrowResultConverter.ts index ec30b6e2..8f4fbc1e 100644 --- a/lib/result/ArrowResultConverter.ts +++ b/lib/result/ArrowResultConverter.ts @@ -47,6 +47,9 @@ const identity: ValueConverter = (value) => value; */ export const DURATION_UNIT_METADATA_KEY = 'databricks.arrow.duration_unit'; const ZERO_BIGINT = BigInt(0); +const SHIFT_32 = BigInt(32); +const SHIFT_64 = BigInt(64); +const SHIFT_96 = BigInt(96); const NS_PER_MICRO = BigInt(1_000); const NS_PER_MILLI = BigInt(1_000_000); const NS_PER_SEC = BigInt(1_000_000_000); @@ -192,6 +195,16 @@ export function bigNumDecimalToString(unscaled: bigint, scale: number): string { return `${negative ? '-' : ''}${digits.slice(0, cut)}.${digits.slice(cut)}`; } +export function decimal128ToBigInt(value: Uint32Array & Parameters[0]): bigint { + if (value.length !== 4) { + return BigInt(bigNumToBigInt(value)); + } + return BigInt.asIntN( + 128, + (BigInt(value[3]) << SHIFT_96) | (BigInt(value[2]) << SHIFT_64) | (BigInt(value[1]) << SHIFT_32) | BigInt(value[0]), + ); +} + /** * Returns the unscaled value of an Arrow Decimal128 as a number. * @@ -485,10 +498,7 @@ export default class ArrowResultConverter implements IResultsProvider const keyType = fieldsMap.entries?.type.children.find((item) => item.name === 'key')?.type; const result = DataType.isDecimal(keyType) ? Object.fromEntries( - Array.from(value, ([key, item]) => [ - bigNumDecimalToString(BigInt(bigNumToBigInt(key)), keyType.scale), - item, - ]), + Array.from(value, ([key, item]) => [bigNumDecimalToString(decimal128ToBigInt(key), keyType.scale), item]), ) : value.toJSON(); const valueField = fieldsMap.entries?.type.children.find((item) => item.name === 'value'); diff --git a/tests/e2e/decimal-map-keys.test.ts b/tests/e2e/decimal-map-keys.test.ts index d7a5474c..5c9ade1f 100644 --- a/tests/e2e/decimal-map-keys.test.ts +++ b/tests/e2e/decimal-map-keys.test.ts @@ -1,59 +1,3 @@ -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'; - -function decimalMapKeysTests(useKernel: boolean) { - describe(`DECIMAL map keys (${useKernel ? 'kernel' : 'Thrift'})`, () => { - for (const preserveBigNumericPrecision of [false, true]) { - it(`preserves exact keys (precision=${preserveBigNumericPrecision})`, async () => { - const client = new DBSQLClient(); - try { - await client.connect({ - host: config.host, - path: config.path, - token: config.token, - useKernel, - preserveBigNumericPrecision, - } as ConnectionOptions & InternalConnectionOptions); - const session = await client.openSession(); - try { - const operation = await session.executeStatement(` - SELECT map(CAST(1.50 AS DECIMAL(10,2)), 'positive', CAST(-0.05 AS DECIMAL(10,2)), NULL) AS amounts, - array(map(CAST(0.0000001 AS DECIMAL(20,7)), 'tiny')) AS nested, - map(CAST('999999999999999999999999999999999999.99' AS DECIMAL(38,2)), 'wide', - CAST('-999999999999999999999999999999999999.99' AS DECIMAL(38,2)), 'negative') AS wide, - map(CAST('-90071992547409.93' AS DECIMAL(38,2)), 'unsafe') AS negative_unsafe, - map(CAST('-123456789012345678.90' AS DECIMAL(38,2)), 'first', - CAST('-123456789012345678.91' AS DECIMAL(38,2)), 'second') AS negative_pair - `); - try { - expect(await operation.fetchAll()).to.deep.equal([ - { - amounts: { '1.50': 'positive', '-0.05': null }, - nested: [{ '0.0000001': 'tiny' }], - wide: { - '999999999999999999999999999999999999.99': 'wide', - '-999999999999999999999999999999999999.99': 'negative', - }, - negative_unsafe: { '-90071992547409.93': 'unsafe' }, - negative_pair: { '-123456789012345678.90': 'first', '-123456789012345678.91': 'second' }, - }, - ]); - } finally { - await operation.close(); - } - } finally { - await session.close(); - } - } finally { - await client.close(); - } - }); - } - }); -} +import decimalMapKeysTests from './utils/decimalMapKeys'; decimalMapKeysTests(false); -decimalMapKeysTests(true); diff --git a/tests/e2e/kernel/decimal-map-keys-e2e.test.ts b/tests/e2e/kernel/decimal-map-keys-e2e.test.ts new file mode 100644 index 00000000..ca18ebe1 --- /dev/null +++ b/tests/e2e/kernel/decimal-map-keys-e2e.test.ts @@ -0,0 +1,3 @@ +import decimalMapKeysTests from '../utils/decimalMapKeys'; + +decimalMapKeysTests(true); diff --git a/tests/e2e/utils/decimalMapKeys.ts b/tests/e2e/utils/decimalMapKeys.ts new file mode 100644 index 00000000..03765d90 --- /dev/null +++ b/tests/e2e/utils/decimalMapKeys.ts @@ -0,0 +1,56 @@ +import { expect } from 'chai'; +import { DBSQLClient } from '../../../lib'; +import { ConnectionOptions } from '../../../lib/contracts/IDBSQLClient'; +import { InternalConnectionOptions } from '../../../lib/contracts/InternalConnectionOptions'; +import config from './config'; + +export default function decimalMapKeysTests(useKernel: boolean) { + describe(`DECIMAL map keys (${useKernel ? 'kernel' : 'Thrift'})`, () => { + for (const preserveBigNumericPrecision of [false, true]) { + it(`preserves exact keys (precision=${preserveBigNumericPrecision})`, async () => { + const client = new DBSQLClient(); + try { + await client.connect({ + host: config.host, + path: config.path, + token: config.token, + useKernel, + preserveBigNumericPrecision, + } as ConnectionOptions & InternalConnectionOptions); + const session = await client.openSession(); + try { + const operation = await session.executeStatement(` + SELECT map(CAST(1.50 AS DECIMAL(10,2)), 'positive', CAST(-0.05 AS DECIMAL(10,2)), NULL) AS amounts, + array(map(CAST(0.0000001 AS DECIMAL(20,7)), 'tiny')) AS nested, + map(CAST('999999999999999999999999999999999999.99' AS DECIMAL(38,2)), 'wide', + CAST('-999999999999999999999999999999999999.99' AS DECIMAL(38,2)), 'negative') AS wide, + map(CAST('-90071992547409.93' AS DECIMAL(38,2)), 'unsafe') AS negative_unsafe, + map(CAST('-123456789012345678.90' AS DECIMAL(38,2)), 'first', + CAST('-123456789012345678.91' AS DECIMAL(38,2)), 'second') AS negative_pair + `); + try { + expect(await operation.fetchAll()).to.deep.equal([ + { + amounts: { '1.50': 'positive', '-0.05': null }, + nested: [{ '0.0000001': 'tiny' }], + wide: { + '999999999999999999999999999999999999.99': 'wide', + '-999999999999999999999999999999999999.99': 'negative', + }, + negative_unsafe: { '-90071992547409.93': 'unsafe' }, + negative_pair: { '-123456789012345678.90': 'first', '-123456789012345678.91': 'second' }, + }, + ]); + } finally { + await operation.close(); + } + } finally { + await session.close(); + } + } finally { + await client.close(); + } + }); + } + }); +} diff --git a/tests/unit/result/ArrowRowMaterialization.test.ts b/tests/unit/result/ArrowRowMaterialization.test.ts index c9e9fd42..bcedc360 100644 --- a/tests/unit/result/ArrowRowMaterialization.test.ts +++ b/tests/unit/result/ArrowRowMaterialization.test.ts @@ -2,7 +2,10 @@ import { deepStrictEqual } from 'assert'; import { expect } from 'chai'; import sinon from 'sinon'; import * as arrow from 'apache-arrow'; -import ArrowResultConverter, { DURATION_UNIT_METADATA_KEY } from '../../../lib/result/ArrowResultConverter'; +import ArrowResultConverter, { + decimal128ToBigInt, + DURATION_UNIT_METADATA_KEY, +} from '../../../lib/result/ArrowResultConverter'; import ArrowResultHandler from '../../../lib/result/ArrowResultHandler'; import { ArrowBatch, getSchemaColumns } from '../../../lib/result/utils'; import { RowMode } from '../../../lib/contracts/IDBSQLSession'; @@ -71,6 +74,48 @@ function decimal(value: string): Uint32Array { return Uint32Array.from([0, 32, 64, 96], (shift) => Number((unsigned >> BigInt(shift)) & BigInt('4294967295'))); } +describe('decimal128ToBigInt', () => { + it('matches Arrow string conversion for signed boundaries and seeded random words', () => { + const limit = BigInt(2) ** BigInt(127); + const unsafe = BigInt(2) ** BigInt(53); + const values = [ + BigInt(0), + BigInt(-1), + limit - BigInt(1), + -limit + BigInt(1), + -limit, + unsafe - BigInt(1), + unsafe + BigInt(1), + -unsafe - BigInt(1), + -unsafe + BigInt(1), + ...[32, 63, 64, 95, 96].flatMap((shift) => { + const boundary = BigInt(2) ** BigInt(shift); + return [boundary - BigInt(1), boundary, -boundary, -boundary - BigInt(1)]; + }), + ].map((value) => decimal(value.toString())); + let seed = 0x657dec; + for (let index = 0; index < 4096; index += 1) { + values.push( + Uint32Array.from({ length: 4 }, () => { + seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; + return seed; + }), + ); + } + for (const words of values) { + const value = arrow.util.BN.decimal(words); + expect(decimal128ToBigInt(value)).to.equal(BigInt(arrow.util.bigNumToString(value))); + } + }); + + it('falls back to Arrow conversion for non-Decimal128 word counts', () => { + for (const words of [new Uint32Array([17, 1]), new Uint32Array([0xffffffff, 0xffffffff])]) { + const value = arrow.util.BN.decimal(words); + expect(decimal128ToBigInt(value)).to.equal(BigInt(arrow.util.bigNumToBigInt(value))); + } + }); +}); + describe('Arrow row materialization', () => { for (const rowMode of ['object', 'array'] as const) { it(`skips BigInt conversion only for safe-integer decimals (${rowMode})`, () => { @@ -286,9 +331,14 @@ describe('Arrow row materialization', () => { : Object.fromEntries(columns.map((column) => [column.field.name, column.expected[rowIndex]])), ); const converter = converterFor(columns, rowMode, preservePrecision); - deepStrictEqual(await converter.fetchNext({ limit: 100 }), expected); + const rows = await converter.fetchNext({ limit: 100 }); + deepStrictEqual(Object.keys(rowMode === 'array' ? rows[0][0] : rows[0].map), expectedKeys); + deepStrictEqual(Object.keys(rowMode === 'array' ? rows[0][1][0] : rows[0].nested[0]), expectedKeys); + deepStrictEqual(rows, expected); const batch = arrow.tableFromIPC(ipc(columns)).batches[0]; const legacyRows = (converter as any).getObjectRows(batch.schema, batch.toArray()); + deepStrictEqual(Object.keys(legacyRows[0].map), expectedKeys); + deepStrictEqual(Object.keys(legacyRows[0].nested[0]), expectedKeys); deepStrictEqual( rowMode === 'array' ? legacyRows.map((row: any) => columns.map((column) => row[column.field.name])) @@ -338,6 +388,33 @@ describe('Arrow row materialization', () => { } for (const preservePrecision of [false, true]) { + it(`keeps scale-0 Decimal128 key enumeration (${rowMode}, precision=${preservePrecision})`, async () => { + const mapType = new arrow.Map_( + new arrow.Field( + 'entries', + new arrow.Struct<{ key: arrow.Decimal; value: arrow.Utf8 }>([ + new arrow.Field('key', new arrow.Decimal(0, 38, 128), false), + new arrow.Field('value', new arrow.Utf8()), + ]), + ), + ); + const columns: Column[] = [ + { + field: new arrow.Field('map', mapType), + thriftType: TTypeId.MAP_TYPE, + values: [new Map(['10', '-7', '2', '-3', '0', '-9'].map((key) => [decimal(key), key]))], + expected: [], + }, + ]; + const converter = converterFor(columns, rowMode, preservePrecision); + const [row] = await converter.fetchNext({ limit: 100 }); + const expectedKeys = ['0', '2', '10', '-7', '-3', '-9']; + deepStrictEqual(Object.keys(rowMode === 'array' ? row[0] : row.map), expectedKeys); + const batch = arrow.tableFromIPC(ipc(columns)).batches[0]; + const [legacyRow] = (converter as any).getObjectRows(batch.schema, batch.toArray()); + deepStrictEqual(Object.keys(legacyRow.map), expectedKeys); + }); + it(`preserves scalar values, types and nulls (${rowMode}, precision=${preservePrecision})`, async () => { const timestamp = new Date('2026-01-02T03:04:05.000Z'); const columns: Column[] = [