diff --git a/CHANGELOG.md b/CHANGELOG.md index d2a9bfc0..56e197a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ - **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) - Fix `fetchAll()` and `fetchChunk()` hanging on column-based results with an empty or missing schema. (#651) - Kernel backend: support SOCKS proxies through the `proxy` option. +- **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. ## 3.1.0 diff --git a/lib/result/ArrowResultConverter.ts b/lib/result/ArrowResultConverter.ts index 52911d5b..a53475fd 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); @@ -194,6 +197,16 @@ export function bigNumDecimalToString(value: bigint | string, scale: number): st 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. * @@ -484,8 +497,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(decimal128ToBigInt(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..5c9ade1f --- /dev/null +++ b/tests/e2e/decimal-map-keys.test.ts @@ -0,0 +1,3 @@ +import decimalMapKeysTests from './utils/decimalMapKeys'; + +decimalMapKeysTests(false); 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 844f6a9e..bb0ab20d 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})`, () => { @@ -240,7 +285,161 @@ 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', + '-99999999999999999999999999999999999999', + '-9007199254740993', + '-12345678901234567890', + '-12345678901234567891', + ]; + const expectedKeys = + scale === 2 + ? [ + '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}`]), + ); + 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); + 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])) + : legacyRows, + 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]); + }); + } + } + } + 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[] = [