Skip to content
Closed
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
3 changes: 3 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,6 @@ jobs:

- name: Run tests
run: pnpm run test

- name: Check Arrow JS numeric type compatibility
run: pnpm exec tsc --ignoreConfig --noEmit --strict --skipLibCheck --target es2022 --module node16 test/types/arrow-numeric.ts
6 changes: 4 additions & 2 deletions docs/api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,10 @@ const table = tableFromArrays({

Create a new column from a provided data array. The data types for the column can be automatically inferred or specified using the *type* argument.

The *type* argument also accepts Apache Arrow JS integer and floating-point descriptors, such as `new Int32()` or `new Float64()` from `apache-arrow`. These are normalized to Flechette data types, so the returned column's `type` is a new Flechette descriptor. Native Flechette types retain their identity. This compatibility also applies to `columnFromValues` and the `types` option of `tableFromArrays`; other data types must use Flechette's [type constructors](data-types).

* *array* (`Array | TypedArray`): The input data as an Array or TypedArray.
* *type*: (`DataType`): The [data type](data-types) for the column. If not specified, type inference is attempted.
* *type*: (`ColumnBuilderType`): The [data type](data-types) for the column. If not specified, type inference is attempted.
* *options* (`object`): Options for building new columns and controlling how values are transformed when extracted from an Arrow binary representation.
* *maxBatchRows* (`number`): The maximum number of rows to include in a single record batch. If the array length exceeds this number, the resulting column will consist of multiple record batches.
* In addition, all [tableFromIPC](#tableFromIPC) extraction options are supported.
Expand All @@ -165,7 +167,7 @@ columnFromArray(
Create a new column by iterating over provided *values*. The *values* argument can either be an iterable collection or a visitor function that applies a callback to successive data values (akin to `Array.forEach`). The data types for the column can be automatically inferred or specified using the *type* argument.

* *values* (`Iterable | (callback: (value: any) => void) => void`): An iterable object or a visitor function that applies a callback to successive data values (akin to `Array.forEach`). In most cases, providing a visitor function will be more efficient than an iterator, so is recommended for larger datasets.
* *type*: (`DataType`): The [data type](data-types) for the column. If not specified, type inference is attempted.
* *type*: (`ColumnBuilderType`): The [data type](data-types) for the column. If not specified, type inference is attempted.
* *options* (`object`): Options for building new columns and controlling how values are transformed when extracted from an Arrow binary representation.
* *maxBatchRows* (`number`): The maximum number of rows to include in a single record batch. If the number of values exceeds this number, the resulting column will consist of multiple record batches.
* In addition, all [tableFromIPC](#tableFromIPC) extraction options are supported.
Expand Down
4 changes: 2 additions & 2 deletions src/build/column-from-array.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* @import { ColumnBuilderOptions, DataType, TypedArray, TypedArrayConstructor } from '../types.js'
* @import { ColumnBuilderOptions, ColumnBuilderType, DataType, TypedArray, TypedArrayConstructor } from '../types.js'
* @import { dictionaryContext } from './builders/dictionary.js'
*/
import { float32Array, float64Array, int16Array, int32Array, int64Array, int8Array, isInt64ArrayType, isTypedArray, uint16Array, uint32Array, uint64Array, uint8Array } from '../util/arrays.js';
Expand All @@ -12,7 +12,7 @@ import { columnFromValues } from './column-from-values.js';
* Create a new column from a provided data array.
* @template T
* @param {Array | TypedArray} array The input data.
* @param {DataType} [type] The data type.
* @param {ColumnBuilderType} [type] The data type.
* If not specified, type inference is attempted.
* @param {ColumnBuilderOptions} [options]
* Builder options for the generated column.
Expand Down
33 changes: 26 additions & 7 deletions src/build/column-from-values.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
/**
* @import { ColumnBuilderOptions, DataType, NullType } from '../types.js'
* @import { ColumnBuilderOptions, ColumnBuilderType, DataType, NullType } from '../types.js'
* @import { dictionaryContext } from './builders/dictionary.js'
*/
import { NullBatch } from '../batch.js';
import { Column } from '../column.js';
import { inferType } from './infer-type.js';
import { builder, builderContext } from './builder.js';
import { Type } from '../constants.js';
import { float, int } from '../data-types.js';
import { isIterable } from '../util/objects.js';

/**
Expand All @@ -15,7 +16,7 @@ import { isIterable } from '../util/objects.js';
* @param {Iterable | ((callback: (value: any) => void) => void)} values
* Either an iterable object or a visitor function that applies a callback
* to successive data values (akin to Array.forEach).
* @param {DataType} [type] The data type.
* @param {ColumnBuilderType} [type] The data type.
* @param {ColumnBuilderOptions} [options]
* Builder options for the generated column.
* @param {ReturnType<typeof dictionaryContext>} [dicts]
Expand All @@ -27,17 +28,17 @@ export function columnFromValues(values, type, options = {}, dicts) {
? callback => { for (const value of values) callback(value); }
: values;

type ??= inferType(visit);
const dataType = normalizeType(type ?? inferType(visit));
const { maxBatchRows = Infinity, ...opt } = options;
let data;

if (type.typeId === Type.Null) {
if (dataType.typeId === Type.Null) {
let length = 0;
visit(() => ++length);
data = nullBatches(type, length, maxBatchRows);
data = nullBatches(dataType, length, maxBatchRows);
} else {
const ctx = builderContext(opt, dicts);
const b = builder(type, ctx).init();
const b = builder(dataType, ctx).init();
const next = b => data.push(b.batch());
data = [];

Expand All @@ -55,7 +56,25 @@ export function columnFromValues(values, type, options = {}, dicts) {
ctx.finish();
}

return new Column(data, type);
return new Column(data, dataType);
}

/**
* Normalize Arrow JS numeric descriptors without mutating the input. Derive
* the backing array from the logical type instead of trusting ArrayType.
* @param {ColumnBuilderType} type
* @returns {DataType}
*/
function normalizeType(type) {
if (type.typeId === Type.Int && !('values' in type) && 'isSigned' in type) {
return int(type.bitWidth, type.isSigned);
}
if (type.typeId === Type.Float && !('values' in type) && 'precision' in type) {
return float(type.precision);
}
// The numeric input types have broad typeId declarations to accommodate
// Arrow JS typings. All other inputs use Flechette's representation.
return /** @type {DataType} */ (type);
}

/**
Expand Down
13 changes: 12 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,17 @@ export interface ColumnBuilderOptions extends ExtractionOptions {
maxBatchRows?: number;
}

/**
* Column input types. Arrow JS integer and floating-point descriptors are
* normalized to Flechette types when building columns. Other types must use
* Flechette's data type representation.
* Arrow JS declares specialized type IDs for numeric subclasses, although
* their runtime IDs are always Int (2) or Float (3), so typeId is a number here.
*/
export type ColumnBuilderType = DataType
| { typeId: number, bitWidth: IntBitWidth, isSigned: boolean }
| { typeId: number, precision: Precision_ };

/**
* Options for building new tables and controlling how values are
* transformed when extracted from an Arrow binary representation.
Expand All @@ -416,7 +427,7 @@ export interface TableBuilderOptions extends ColumnBuilderOptions {
/**
* A map from column names to Arrow data types.
*/
types?: Record<string, DataType>;
types?: Record<string, ColumnBuilderType>;
}

/**
Expand Down
56 changes: 56 additions & 0 deletions test/arrow-numeric-types.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { describe, it, expect } from 'vitest';
import * as arrow from 'apache-arrow';
import { columnFromArray, columnFromValues, float64, int32, tableFromArrays, tableFromColumns, tableFromIPC, tableToIPC } from '../src/index.js';

const cases = [
[new arrow.Int8(), [-128, null, 0, 127]],
[new arrow.Int16(), [-32768, null, 0, 32767]],
[new arrow.Int32(), [-2147483648, null, 0, 2147483647]],
[new arrow.Int64(), [-9223372036854775808n, null, 0n, 9223372036854775807n]],
[new arrow.Uint8(), [0, null, 1, 255]],
[new arrow.Uint16(), [0, null, 1, 65535]],
[new arrow.Uint32(), [0, null, 1, 4294967295]],
[new arrow.Uint64(), [0n, null, 1n, 18446744073709551615n]],
[new arrow.Float16(), [-1.5, null, 0, 65504]],
[new arrow.Float32(), [-1.5, null, 0, 65504]],
[new arrow.Float64(), [-1.25, null, 0, 1e100]]
];
const options = { useBigInt: true, maxBatchRows: 2 };

describe('Arrow JS numeric type inputs', () => {
for (const [type, values] of cases) {
it(`builds ${type} columns from arrays and iterables`, () => {
Object.freeze(type);
const column = columnFromArray(values, type, options);
expect([...column]).toStrictEqual(values);
expect([...columnFromValues(values.values(), type, options)]).toStrictEqual(values);
expect(column.type).not.toBe(type);
expect(column.type.values).toBe(type.ArrayType);
if (type.typeId === arrow.Type.Int) {
expect(column.type.signed).toBe(type.isSigned);
}
});

for (const format of ['stream', 'file']) {
it(`preserves ${type} values and schema in IPC ${format}`, () => {
const table = tableFromArrays({ x: values }, { ...options, types: { x: type } });
const bytes = tableToIPC(table, { format });
const decoded = tableFromIPC(bytes, options).getChild('x');
expect([...decoded]).toStrictEqual(values);
const reference = arrow.tableFromIPC(bytes).getChild('x');
expect([...reference]).toStrictEqual(values);
expect(reference.type.toString()).toBe(type.toString());
});
}
}

it('preserves native type identity and typed-array input values', () => {
for (const type of [Object.freeze(int32()), Object.freeze(float64())]) {
const column = columnFromArray([-1, 0, 1], type);
expect(column.type).toBe(type);
expect([...column]).toStrictEqual([-1, 0, 1]);
}
const column = columnFromArray(Int32Array.of(-1000, 0, 1000), new arrow.Int32());
expect(tableFromColumns({ x: column }).toColumns().x).toStrictEqual(Int32Array.of(-1000, 0, 1000));
});
});
24 changes: 24 additions & 0 deletions test/types/arrow-numeric.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Run after `pnpm run build`:
// pnpm exec tsc --ignoreConfig --noEmit --strict --skipLibCheck --target es2022 --module node16 test/types/arrow-numeric.ts
import * as arrow from 'apache-arrow';
import { columnFromArray, columnFromValues, int32, tableFromArrays } from '../../dist/types/index-types.js';
import type { ColumnBuilderType, DataType } from '../../dist/types/index-types.js';

const types: ColumnBuilderType[] = [
new arrow.Int8(), new arrow.Int16(), new arrow.Int32(), new arrow.Int64(),
new arrow.Uint8(), new arrow.Uint16(), new arrow.Uint32(), new arrow.Uint64(),
new arrow.Float16(), new arrow.Float32(), new arrow.Float64(), int32()
];
for (const type of types) {
const column = columnFromArray([1, 2], type);
const canonical: DataType = column.type;
columnFromValues([1, 2].values(), type);
tableFromArrays({ x: [1, 2] }, { types: { x: type } });
columnFromArray([1, 2], canonical);
}

// Compatibility is deliberately limited to numeric descriptors.
// @ts-expect-error Arrow JS decimal buffers use a different representation.
columnFromArray([1], new arrow.Decimal(2, 10));
// @ts-expect-error Integer signedness must be specified.
columnFromArray([1], { typeId: 2, bitWidth: 32 });
Loading