diff --git a/docs/src/js/functions/makeArrowTable.md b/docs/src/js/functions/makeArrowTable.md index 949f1ceff..f4abace62 100644 --- a/docs/src/js/functions/makeArrowTable.md +++ b/docs/src/js/functions/makeArrowTable.md @@ -42,6 +42,7 @@ rules are as follows: - bigint => Int64 - String => Utf8 - Buffer => Binary + - Date => Timestamp (millisecond) - Record => Struct - Array => List diff --git a/nodejs/__test__/arrow.test.ts b/nodejs/__test__/arrow.test.ts index 1dbb14f5a..6acb3ba20 100644 --- a/nodejs/__test__/arrow.test.ts +++ b/nodejs/__test__/arrow.test.ts @@ -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 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>) => + 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 from Uint8Array values", async function () { const table = makeArrowTable([ { id: "a", vector: new Uint8Array([1, 2, 3]) }, diff --git a/nodejs/lancedb/arrow.ts b/nodejs/lancedb/arrow.ts index b8189fa2a..a7b0e5d86 100644 --- a/nodejs/lancedb/arrow.ts +++ b/nodejs/lancedb/arrow.ts @@ -377,6 +377,7 @@ export class MakeArrowTableOptions { * - bigint => Int64 * - String => Utf8 * - Buffer => Binary + * - Date => Timestamp (millisecond) * - Record => Struct * - Array => List * @example @@ -846,6 +847,115 @@ function makeListVector(lists: unknown[][]): Vector { 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) { + 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) { diff --git a/nodejs/lancedb/schema.ts b/nodejs/lancedb/schema.ts index 3e225464f..bb6648d5e 100644 --- a/nodejs/lancedb/schema.ts +++ b/nodejs/lancedb/schema.ts @@ -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}. ` +