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
+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]) },