fix(node): infer a timestamp type for Date values (#5232)

`createTable` and `makeArrowTable` reject a JavaScript `Date` when no
schema is given:

```ts
await db.createTable("events", [{ id: 1, created: new Date() }]);
// Error: Failed to infer data type for field created at row 0. Consider providing an explicit schema.
```

Row validation already lets `Date` through as a supported value, and the
same rows work with an explicit `Timestamp` schema, but `inferType` has
no branch for it, so inference gives up.

This change:

- infers `Timestamp<MILLISECOND>` for a `Date`, which is also what
Apache Arrow's own `vectorFromArray` infers and matches the precision of
a JS `Date`. A list of dates is inferred as a list even when the column
name looks like a vector column;
- writes `Timestamp(ms)` columns, and lists of them at any depth, as
signed 64-bit values in `makeVector`. `apache-arrow@15.0.0` rounds the
high 32 bits of a negative timestamp toward zero, so `new Date(-1)` came
back as 4294967295. This already affected an explicit `Timestamp(ms)`
schema on Arrow 15; inference would have made it easier to hit. `Date`,
integer and bigint values take the new path; anything else (fractional
numbers, strings, list values that are not arrays or typed arrays) is
left to Arrow exactly as before;
- rejects an Invalid Date with a clear error. Arrow 15 stored it as
1970-01-01 and newer versions threw a BigInt conversion error;
- documents the new rule in the `makeArrowTable` docstring and the
generated API page.

Not changed (explicit schemas only, behaviour as before this PR):
timestamp units other than milliseconds, timestamps inside a
`List<Struct>`, `FixedSizeList` or `Map`, and `Date` query parameters in
`sql.ts`. On Arrow 15 these still go through Arrow's conversion. I can
follow up on them separately if wanted.

Tested:
- New tests in `__test__/arrow.test.ts`: the type is inferred; values
and nulls round-trip; a `Date` mixed with a string is still rejected;
dates before 1970 survive IPC as scalars, in lists, nested lists and
structs, with and without a schema; epoch numbers, bigints and typed
arrays keep working in explicit timestamp columns; Invalid Date is
rejected in every shape.
- `jest __test__/arrow.test.ts` passes with `apache-arrow` resolved to
15.0.0, 16.0.0, 17.0.0 and 21.2.0 (swapped the way the `arrow-compat` CI
job does). On 15.0.0 the pre-1970 tests fail without the workaround. CI
does not run Arrow 15, so on newer versions the Invalid Date test is
what fails if a shape stops reaching the new writer.
- `jest __test__/table.test.ts`, `biome ci .`, `tsc -b` and `pnpm run
docs` pass.
- Checked by hand that `createTable` then `add` with `Date` values
stores and returns them.

I ran the TypeScript tests against the published 0.42.0-beta.34 native
binary; I did not rebuild the Rust side, which this change does not
touch.
This commit is contained in:
Ayanna Bansal
2026-11-30 20:38:59 +08:00
committed by GitHub
parent 04bf27af9d
commit 14e49a6710
4 changed files with 302 additions and 1 deletions
+1
View File
@@ -42,6 +42,7 @@ rules are as follows:
- bigint => Int64
- String => Utf8
- Buffer => Binary
- Date => Timestamp (millisecond)
- Record<String, any> => Struct
- Array<any> => List
+168
View File
@@ -159,6 +159,7 @@ describe.each(arrowVersions)("Arrow %#", (arrow: ApacheArrow) => {
Float32,
FixedSizeList,
Precision,
TimestampMillisecond,
tableFromIPC,
DataType,
Dictionary,
@@ -554,6 +555,173 @@ describe.each(arrowVersions)("Arrow %#", (arrow: ApacheArrow) => {
);
});
it("will infer Timestamp<MILLISECOND> from Date values", function () {
const first = new Date("2024-01-02T03:04:05.678Z");
const table = makeArrowTable([
{ id: "a", created: first },
{ id: "b", created: null },
{ id: "c", created: new Date(0) },
]);
const created = table.getChild("created");
expect(created?.type.toString()).toEqual(
new TimestampMillisecond().toString(),
);
expect(Number(created?.get(0))).toBe(first.getTime());
expect(created?.get(1)).toBeNull();
expect(Number(created?.get(2))).toBe(0);
expect(() =>
makeArrowTable([{ created: first }, { created: "yesterday" }]),
).toThrow("Failed to infer schema for data.");
});
// Arrow 15 rounds the high 32 bits of a negative timestamp toward zero, so
// it comes back 2^32 ms late. CI resolves `apache-arrow` to 19 and later;
// swap in 15 to see these fail without the workaround.
it("preserves dates before 1970 through IPC", async function () {
const dates = [
new Date(-1),
null,
new Date("1890-06-15T12:00:00.000Z"),
new Date("2024-01-02T03:04:05.678Z"),
];
const millis = dates.map((d) => (d === null ? null : d.getTime()));
const read = (table: Awaited<ReturnType<typeof currentTableFromIPC>>) =>
dates.map((_, i) => {
const value = table.getChild("created")?.get(i);
return value === null ? null : Number(value);
});
const inferred = currentTableFromIPC(
await fromDataToBuffer(dates.map((created) => ({ created }))),
);
expect(read(inferred)).toEqual(millis);
const schema = new Schema([
new Field("created", new TimestampMillisecond(), true),
]);
const withSchema = currentTableFromIPC(
await fromDataToBuffer(
dates.map((created) => ({ created })),
undefined,
schema,
),
);
expect(read(withSchema)).toEqual(millis);
});
it("preserves dates before 1970 inside lists and structs through IPC", async function () {
const early = new Date(-1);
const older = new Date("1890-06-15T12:00:00.000Z");
const late = new Date("2024-01-02T03:04:05.678Z");
const rows = [
{
events: [early, null, late],
nested: [[older], [], [early, late]],
info: { at: older, history: [early] },
},
{
events: null,
nested: [[late]],
info: { at: null, history: [] },
},
{
events: [],
nested: null,
info: { at: late, history: [older, late] },
},
];
// biome-ignore lint/suspicious/noExplicitAny: nested Arrow values
const plain = (value: any): unknown => {
if (value === null || value === undefined) return null;
if (typeof value === "bigint" || typeof value === "number") {
return Number(value);
}
if (value instanceof Date) return value.getTime();
if (Array.isArray(value)) return value.map(plain);
// Arrow lists and struct rows both turn into plain JS with toJSON.
if (typeof value.toJSON === "function") return plain(value.toJSON());
return Object.fromEntries(
Object.entries(value).map(([key, item]) => [key, plain(item)]),
);
};
const result = currentTableFromIPC(await fromDataToBuffer(rows));
for (const column of ["events", "nested", "info"] as const) {
expect(
rows.map((_, i) => plain(result.getChild(column)?.get(i))),
).toEqual(rows.map((row) => plain(row[column])));
}
});
// On every Arrow version this also fails if a Date-bearing shape stops
// going through the signed timestamp writer.
it("rejects an Invalid Date instead of storing a wrong timestamp", function () {
const invalid = new Date("not a date");
const message = "Cannot store an Invalid Date in a timestamp column";
for (const row of [
{ created: invalid },
{ events: [invalid] },
{ nested: [[invalid]] },
{ info: { at: invalid } },
{ info: { history: [invalid] } },
]) {
expect(() => makeArrowTable([row])).toThrow(message);
}
const schema = new Schema([
new Field("created", new TimestampMillisecond(), true),
new Field(
"events",
new List(new Field("item", new TimestampMillisecond(), true)),
true,
),
]);
expect(() => makeArrowTable([{ created: invalid }], { schema })).toThrow(
message,
);
expect(() => makeArrowTable([{ events: [invalid] }], { schema })).toThrow(
message,
);
});
it("will infer a list, not a vector, for dates in a vector-named column", function () {
const date = new Date("2024-01-02T03:04:05.678Z");
const table = makeArrowTable([{ ["embedding_dates"]: [date, date] }]);
const column = table.getChild("embedding_dates");
expect(DataType.isList(column?.type)).toBe(true);
expect(Number(column?.get(0).get(1))).toBe(date.getTime());
});
it("keeps epoch numbers and typed arrays working in timestamp columns", async function () {
const schema = new Schema([
new Field("at", new TimestampMillisecond(), true),
new Field(
"stamps",
new List(new Field("item", new TimestampMillisecond(), true)),
true,
),
]);
const rows = [
{ at: new Date(-1), stamps: [0, -1, new Date(-2), null] },
{ at: -3, stamps: Float64Array.from([5, -6]) },
{ at: -4n, stamps: null },
{ at: null, stamps: [] },
];
const result = currentTableFromIPC(
await fromDataToBuffer(rows, undefined, schema),
);
const numbers = (column: string) =>
rows.map((_, i) => {
const value = result.getChild(column)?.get(i);
if (value === null) return null;
return typeof value === "bigint" || typeof value === "number"
? Number(value)
: [...value].map((item) => (item === null ? null : Number(item)));
});
expect(numbers("at")).toEqual([-1, -3, -4, null]);
expect(numbers("stamps")).toEqual([[0, -1, -2, null], [5, -6], null, []]);
});
it("will infer FixedSizeList<Uint8> from Uint8Array values", async function () {
const table = makeArrowTable([
{ id: "a", vector: new Uint8Array([1, 2, 3]) },
+119
View File
@@ -377,6 +377,7 @@ export class MakeArrowTableOptions {
* - bigint => Int64
* - String => Utf8
* - Buffer => Binary
* - Date => Timestamp (millisecond)
* - Record<String, any> => Struct
* - Array<any> => List
* @example
@@ -846,6 +847,115 @@ function makeListVector(lists: unknown[][]): Vector<unknown> {
return listBuilder.finish().toVector();
}
/** True for Timestamp(ms) and for a list, at any depth, of Timestamp(ms). */
function holdsMillisecondTimestamps(type: DataType): boolean {
if (DataType.isTimestamp(type)) {
return type.unit === TimeUnit.MILLISECOND;
}
return isList(type) && holdsMillisecondTimestamps(type.children[0].type);
}
/**
* Build a Timestamp(ms) vector by writing the 64-bit values directly.
*
* Arrow 15 rounds the high 32 bits of a negative timestamp toward zero, so a
* date before 1970 comes back 2^32 ms (about 49.7 days) late. The bytes
* written here are the same in every supported Arrow version.
*
* Returns undefined when a value is not a Date, an integer or a bigint, so
* the caller can leave those inputs to Arrow as before.
*/
function makeSignedTimestampVector(
values: unknown[],
type: DataType,
): Vector | undefined {
const millis = new BigInt64Array(values.length);
const validity: boolean[] = [];
for (const [i, value] of values.entries()) {
if (value === null || value === undefined) {
validity.push(false);
continue;
}
if (value instanceof Date) {
const time = value.getTime();
if (Number.isNaN(time)) {
// Arrow 15 would store 1970-01-01; newer versions throw a BigInt
// conversion error that does not name the cause.
throw new Error("Cannot store an Invalid Date in a timestamp column");
}
millis[i] = BigInt(time);
} else if (typeof value === "bigint") {
millis[i] = value;
} else if (typeof value === "number" && Number.isInteger(value)) {
millis[i] = BigInt(value);
} else {
return undefined;
}
validity.push(true);
}
const nullCount = validity.filter((valid) => !valid).length;
return arrowMakeVector(
makeData({
type: type as Timestamp,
length: values.length,
nullCount,
nullBitmap: nullCount > 0 ? arrowUtil.packBools(validity) : undefined,
// Arrow 15 and 16 type this buffer as Int32Array; same bytes.
data: millis as unknown as Timestamp["TArray"],
}),
);
}
/**
* Build a list of Timestamp(ms) so its items go through
* `makeSignedTimestampVector`; Arrow's own list builder would skip it.
*
* Returns undefined when a list is neither an array nor a typed array, so
* the caller can leave those inputs to Arrow as before.
*/
function makeTimestampListVector(
values: unknown[],
type: List,
): Vector | undefined {
const childField = type.children[0];
const flattened: unknown[] = [];
const validity: boolean[] = [];
const offsets: number[] = [0];
for (const value of values) {
if (value === null || value === undefined) {
validity.push(false);
} else if (Array.isArray(value)) {
validity.push(true);
for (const item of value) flattened.push(item);
} else if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {
validity.push(true);
for (const item of value as unknown as Iterable<unknown>) {
flattened.push(item);
}
} else {
return undefined;
}
offsets.push(flattened.length);
}
const child = makeVector(
flattened,
childField.type,
undefined,
childField.nullable,
);
const nullCount = validity.filter((valid) => !valid).length;
return arrowMakeVector(
makeData({
type,
length: values.length,
nullCount,
nullBitmap: nullCount > 0 ? arrowUtil.packBools(validity) : undefined,
valueOffsets: Int32Array.from(offsets),
child: child.data[0],
}),
);
}
/** Helper function to convert an Array of JS values to an Arrow Vector */
function makeVector(
values: unknown[],
@@ -875,6 +985,15 @@ function makeVector(
}
}
if (holdsMillisecondTimestamps(type)) {
const vector = isList(type)
? makeTimestampListVector(values, type)
: makeSignedTimestampVector(values, type);
if (vector !== undefined) {
return vector;
}
}
// No need for inference, let Arrow create it
if (type instanceof Int) {
if (DataType.isInt(type) && type.bitWidth === 64) {
+14 -1
View File
@@ -15,6 +15,7 @@ import {
List,
Schema,
Struct,
TimestampMillisecond,
Utf8,
util as arrowUtil,
} from "apache-arrow";
@@ -227,6 +228,9 @@ class SchemaInferrer {
if (typeof value === "boolean") {
return new Bool();
}
if (value instanceof Date) {
return new TimestampMillisecond();
}
if (value instanceof Buffer) {
return new Binary();
}
@@ -257,7 +261,9 @@ class SchemaInferrer {
return undefined;
}
return nameSuggestsVectorColumn(path[path.length - 1])
// A list of dates is never a vector, whatever the column is called.
return nameSuggestsVectorColumn(path[path.length - 1]) &&
!holdsTimestamps(itemType)
? new FixedSizeList(value.length, new Field("item", new Float32(), true))
: new List(new Field("item", itemType, true));
}
@@ -636,6 +642,13 @@ function schemaInferenceError(
);
}
function holdsTimestamps(type: DataType): boolean {
return (
DataType.isTimestamp(type) ||
(DataType.isList(type) && holdsTimestamps(type.children[0].type))
);
}
function typeInferenceError(path: string[], row: number): Error {
return new Error(
`Failed to infer data type for field ${path.join(".")} at row ${row}. ` +