Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
fix: handle Arrow Int64 BigInt values in accessors and filters (#3641)
Igor Dykhta8c03ee4978e7
diff --git a/src/layers/src/aggregation-layer.ts b/src/layers/src/aggregation-layer.tsindex 28ebfbdec..0967773f2 100644--- a/src/layers/src/aggregation-layer.ts+++ b/src/layers/src/aggregation-layer.ts@@ -314,7 +314,7 @@ export default class AggregationLayer extends Layer {accu[field.name] = {measure,value: aggregate(object.points, measure, (d: {index: number}) => {- return dataContainer.valueAt(d.index, field.fieldIdx);+ return field.valueAccessor(d);})};return accu;@@ -593,10 +593,7 @@ export default class AggregationLayer extends Layer {arr.some(v => v !== 0));- const getFilterValue = gpuFilter.filterValueAccessor(dataContainer)(- this.gpuFilterGetIndex,- this.gpuFilterGetData- );+ const getFilterValue = gpuFilter.filterValueAccessor(dataContainer)(this.gpuFilterGetIndex);const filterData = hasFilter? getFilterDataFunc(gpuFilter.filterRange, getFilterValue): undefined;diff --git a/src/layers/src/flow-layer/flow-layer.ts b/src/layers/src/flow-layer/flow-layer.tsindex ab116d290..7333056bb 100644--- a/src/layers/src/flow-layer/flow-layer.ts+++ b/src/layers/src/flow-layer/flow-layer.ts@@ -16,6 +16,7 @@ import {Datasets, KeplerTable} from '@kepler.gl/table';import {ColumnLabels,ColumnPairs,+ Field,SupportedColumnMode,VisConfigBoolean,VisConfigNumber,@@ -313,9 +314,12 @@ export default class FlowLayer extends Layer {private getLocationFromPosition = (pos: number[]) =>this._locationsByLatLon?.[FlowLayer.getLatLonKey(pos)];- private getMagnitude = (dataContainer: DataContainerInterface) => (rowIndex: number) => {+ private getMagnitude = (fields: Field[]) => (rowIndex: number) => {const fieldIdx = this.config.columns.count?.fieldIdx;- return fieldIdx != null && fieldIdx >= 0 ? dataContainer.valueAt(rowIndex, fieldIdx) : 1;+ if (fieldIdx == null || fieldIdx < 0) {+ return 1;+ }+ return fields[fieldIdx].valueAccessor({index: rowIndex});};private getSourceName = (dataContainer: DataContainerInterface, d: {index: number}) => {@@ -385,7 +389,7 @@ export default class FlowLayer extends Layer {const getLocationWeight = makeLocationWeightGetter(flowIndices, {getFlowOriginId,getFlowDestId,- getFlowMagnitude: this.getMagnitude(dataContainer)+ getFlowMagnitude: this.getMagnitude(dataset.fields)});const clusterLevels = clusterLocations(locations, flowmapDataAccessors, getLocationWeight, {@@ -396,14 +400,14 @@ export default class FlowLayer extends Layer {}calculateDataAttribute(- {dataContainer, filteredIndex}: KeplerTable,+ {dataContainer, filteredIndex, fields}: KeplerTable,getPosition: (d: any) => number[]): FlowDatum[] {const data: FlowDatum[] = [];const datum = {index: 0};const getSource = this.getSourcePosition(dataContainer);const getTarget = this.getTargetPosition(dataContainer);- const getMag = this.getMagnitude(dataContainer);+ const getMag = this.getMagnitude(fields);for (let i = 0; i < filteredIndex.length; i++) {const index = filteredIndex[i];datum.index = index;@@ -456,15 +460,7 @@ export default class FlowLayer extends Layer {diffUpdateTriggers(filterUpdateTriggers, this._oldFilterUpdateTriggers);if (filterChanged || dataChanged) {const indexAccessor = (d: FlowDatum) => d.index;- const valueAccessor = (- dc: DataContainerInterface,- d: {index: number},- fieldIndex: number- ) => dc.valueAt(d.index, fieldIndex);- const getFilterValue = gpuFilter.filterValueAccessor(dataContainer)(- indexAccessor,- valueAccessor- );+ const getFilterValue = gpuFilter.filterValueAccessor(dataContainer)(indexAccessor);resultingFlows = resultingFlows.filter(getFilterDataFunc(filterRange, getFilterValue));}this._oldFilterUpdateTriggers = filterUpdateTriggers;@@ -584,7 +580,7 @@ export default class FlowLayer extends Layer {object: Record<string, any>;fieldValues: Array<{labelMessage: string; value: any}>;} | null {- const fmt = d3Format(TOOLTIP_FORMATS.DECIMAL_COMMA.format);+ const fmt = v => d3Format(TOOLTIP_FORMATS.DECIMAL_COMMA.format)(Number(v));switch (object?.type) {case PickingType.LOCATION:return {diff --git a/src/layers/src/geojson-layer/geojson-layer.ts b/src/layers/src/geojson-layer/geojson-layer.tsindex d344e6e55..1e5765ef1 100644--- a/src/layers/src/geojson-layer/geojson-layer.ts+++ b/src/layers/src/geojson-layer/geojson-layer.ts@@ -520,7 +520,7 @@ export default class GeoJsonLayer extends Layer {return {};}const {textLabel} = this.config;- const {gpuFilter, dataContainer} = datasets[this.config.dataId];+ const {gpuFilter, dataContainer, fields} = datasets[this.config.dataId];const {data, triggerChanged} = this.updateData(datasets, oldLayerData);// Text labels are only supported in GEOJSON column mode where properties.index@@ -547,7 +547,8 @@ export default class GeoJsonLayer extends Layer {let filterValueAccessor;let dataAccessor;if (this.config.columnMode === COLUMN_MODE_GEOJSON) {- filterValueAccessor = (dc, d, fieldIndex) => dc.valueAt(d.properties.index, fieldIndex);+ filterValueAccessor = (dc, d, fieldIndex) =>+ fields[fieldIndex].valueAccessor({index: d.properties.index});// For GEOJSON mode, properties.index is the row index in the data containerdataAccessor = () => d => ({index: d.properties.index});} else {@@ -577,10 +578,7 @@ export default class GeoJsonLayer extends Layer {indexAccessor,filterValueAccessor),- textLabelFilterValue: gpuFilter.filterValueAccessor(dataContainer)(- textLabelIndexAccessor,- (dc, d, fieldIndex) => dc.valueAt(d.index, fieldIndex)- ),+ textLabelFilterValue: gpuFilter.filterValueAccessor(dataContainer)(textLabelIndexAccessor),getFiltered: isFilteredAccessor,textLabelFiltered: textLabelFilteredAccessor,textLabels,diff --git a/src/layers/src/heatmap-layer/heatmap-layer.ts b/src/layers/src/heatmap-layer/heatmap-layer.tsindex 5f7cd2dab..eabf1289c 100644--- a/src/layers/src/heatmap-layer/heatmap-layer.ts+++ b/src/layers/src/heatmap-layer/heatmap-layer.ts@@ -524,8 +524,7 @@ class HeatmapLayer extends Layer {let filteredData = data;if (hasFilter) {const getFilterValue = gpuFilter.filterValueAccessor(dataContainer)(- (d: {index: number}) => d.index,- (dc, d, fieldIndex) => dc.valueAt(d.index, fieldIndex)+ (d: {index: number}) => d.index);const filterFunc = getFilterDataFunc(gpuFilter.filterRange, getFilterValue);filteredData = data.filter(filterFunc);diff --git a/src/layers/src/trip-layer/trip-layer.ts b/src/layers/src/trip-layer/trip-layer.tsindex 3987dc2d2..ca9f26180 100644--- a/src/layers/src/trip-layer/trip-layer.ts+++ b/src/layers/src/trip-layer/trip-layer.ts@@ -626,7 +626,7 @@ export default class TripLayer extends Layer {switch (this.config.columnMode) {case COLUMN_MODE_GEOJSON: {valueAccessor = (dc: DataContainerInterface, f, fieldIndex: number) => {- return dc.valueAt(f.properties.index, fieldIndex);+ return fields[fieldIndex].valueAccessor({index: f.properties.index});};const textLabelAccessor = tl => dc => {const {field} = tl;diff --git a/src/table/src/gpu-filter-utils.ts b/src/table/src/gpu-filter-utils.tsindex 15d58bec5..77e00b6a9 100644--- a/src/table/src/gpu-filter-utils.ts+++ b/src/table/src/gpu-filter-utils.ts@@ -140,21 +140,13 @@ function getEmptyFilterRange() {*/const defaultGetIndex = d => d.index;-/**- * Returns value at the specified row from the data container.- * @param dc Data container.- * @param d Data element with row index info.- * @param fieldIndex Column index in the data container.- * @returns- */-const defaultGetData = (dc: DataContainerInterface, d: any, fieldIndex: number) => {- return dc.valueAt(d.index, fieldIndex);-};-const getFilterValueAccessor =(channels: (Filter | undefined)[], dataId: string, fields: any[]) =>(dc: DataContainerInterface) =>- (getIndex = defaultGetIndex, getData = defaultGetData) =>+ (+ getIndex = defaultGetIndex,+ getData?: (dc: DataContainerInterface, d: any, fieldIndex: number) => any+ ) =>(d, objectInfo?: {index: number}) => {// for empty channel, value is 0 and min max would be [0, 0]const channelValues = channels.map(filter => {@@ -167,7 +159,9 @@ const getFilterValueAccessor =let value;// d can be undefined when called from attribute updater from deck,// when data is an ArrowTable, so use objectInfo instead.- const data = getData(dc, d || objectInfo, fieldIndex);+ const datum = d || objectInfo;+ // field.valueAccessor is Number() for Int64 columns; valueAt stays raw BigInt.+ const data = getData ? getData(dc, datum, fieldIndex) : field.valueAccessor(datum);if (typeof data === 'function') {value = data(field);} else {diff --git a/src/table/src/kepler-table.ts b/src/table/src/kepler-table.tsindex 96fa4e0ec..d5235a803 100644--- a/src/table/src/kepler-table.ts+++ b/src/table/src/kepler-table.ts@@ -107,19 +107,24 @@ export type TimeFieldFilterProps = TimeRangeFieldDomain & {// Unique identifier of each fieldconst FID_KEY = 'name';+function readFieldValue(+ fieldIdx: number,+ dc: DataContainerInterface,+ // An object with row index or a materialized row array (for materialized hover info from trip layer)+ d: {index: number} | any[]+) {+ return Array.isArray(d) ? d[fieldIdx] : dc.valueAt(d.index, fieldIdx);+}+export function maybeToDate(isTime: boolean,fieldIdx: number,format: string,dc: DataContainerInterface,- // An object with row index or a materialized row array (for materialized hover info from trip layer)d: {index: number} | any[]) {- if (isTime) {- return timeToUnixMilli(Array.isArray(d) ? d[fieldIdx] : dc.valueAt(d.index, fieldIdx), format);- }-- return Array.isArray(d) ? d[fieldIdx] : dc.valueAt(d.index, fieldIdx);+ const value = readFieldValue(fieldIdx, dc, d);+ return isTime ? timeToUnixMilli(value, format) : value;}/**@@ -778,20 +783,33 @@ export function copyTableAndUpdate(}, copyTable(original));}+/**+ * Arrow Int64/Uint64 columns yield JS BigInt. Detect from the column type once+ * at bind time so other columns keep the existing accessor with no extra checks.+ */+function isInt64ArrowColumn(dc: DataContainerInterface, fieldIdx: number): boolean {+ const type = (dc.getColumn?.(fieldIdx) as {type?: {bitWidth?: number; isSigned?: boolean}})+ ?.type;+ return type?.bitWidth === 64 && typeof type.isSigned === 'boolean';+}+export function getFieldValueAccessor<F extends {type?: Field['type'];format?: Field['format'];}>(f: F, i: number, dc: DataContainerInterface) {- return maybeToDate.bind(- null,- // is time- f.type === ALL_FIELD_TYPES.timestamp,- i,- f.format || '',- dc- );+ if (f.type === ALL_FIELD_TYPES.timestamp) {+ const format = f.format || '';+ return (d: {index: number} | any[]) => timeToUnixMilli(readFieldValue(i, dc, d), format);+ }+ if (isInt64ArrowColumn(dc, i)) {+ return (d: {index: number} | any[]) => {+ const value = readFieldValue(i, dc, d);+ return value == null ? value : Number(value);+ };+ }+ return readFieldValue.bind(null, i, dc);}export default KeplerTable;diff --git a/src/utils/src/data-utils.ts b/src/utils/src/data-utils.tsindex 2d054ef8f..b2d713678 100644--- a/src/utils/src/data-utils.ts+++ b/src/utils/src/data-utils.ts@@ -415,12 +415,14 @@ export function applyDefaultFormat(tooltipFormat: TooltipFormat): (v: any) => stswitch (tooltipFormat.type) {case TOOLTIP_FORMAT_TYPES.DECIMAL:- return d3Format(tooltipFormat.format);+ return formatNumeric(tooltipFormat.format);case TOOLTIP_FORMAT_TYPES.DATE:case TOOLTIP_FORMAT_TYPES.DATE_TIME:return datetimeFormatter(null)(tooltipFormat.format);- case TOOLTIP_FORMAT_TYPES.PERCENTAGE:- return v => `${d3Format(TOOLTIP_FORMATS.DECIMAL_DECIMAL_FIXED_2.format)(v)}%`;+ case TOOLTIP_FORMAT_TYPES.PERCENTAGE: {+ const format = formatNumeric(TOOLTIP_FORMATS.DECIMAL_DECIMAL_FIXED_2.format);+ return v => `${format(v)}%`;+ }case TOOLTIP_FORMAT_TYPES.BOOLEAN:return getBooleanFormatter(tooltipFormat.format);default:@@ -443,7 +445,7 @@ export function applyCustomFormat(format, field: {type?: string}): FieldFormatteswitch (field.type) {case ALL_FIELD_TYPES.real:case ALL_FIELD_TYPES.integer:- return d3Format(format);+ return formatNumeric(format);case ALL_FIELD_TYPES.date:case ALL_FIELD_TYPES.timestamp:return datetimeFormatter(null)(format);@@ -452,6 +454,12 @@ export function applyCustomFormat(format, field: {type?: string}): FieldFormatte}}+/** d3-format cannot take BigInt; Int64 table cells are still raw bigint from valueAt. */+function formatNumeric(spec: string): FieldFormatter {+ const format = d3Format(spec);+ return v => format(Number(v));+}+function formatLargeNumber(n) {// SI-prefix with 4 significant digitsreturn d3Format('.4~s')(n);diff --git a/src/utils/src/filter-utils.ts b/src/utils/src/filter-utils.tsindex 22241f419..2eb5238b0 100644--- a/src/utils/src/filter-utils.ts+++ b/src/utils/src/filter-utils.ts@@ -903,12 +903,12 @@ export function getColumnFilterProps<K extends KeplerTableModel<K, L>, L>(return {lineChart: {}, yAxis};}- // return lineChart+ const yAccessor = dataset.fields[fieldIdx].valueAccessor;const series = dataset.dataContainer.map(- (row, rowIndex) => ({+ (_row, rowIndex) => ({x: mappedValue[rowIndex],- y: row.valueAt(fieldIdx)+ y: yAccessor({index: rowIndex})}),true)diff --git a/src/utils/src/plot.ts b/src/utils/src/plot.tsindex bef9d3bde..d5475c65d 100644--- a/src/utils/src/plot.ts+++ b/src/utils/src/plot.ts@@ -376,14 +376,14 @@ const getAgregationType = (field, aggregation) => {return aggregation;};-const getAggregationAccessor = (field, dataContainer: DataContainerInterface, fields) => {+const getAggregationAccessor = (field, fields) => {if (isPercentField(field)) {const numeratorIdx = fields.findIndex(f => f.name === field.metadata.numerator);const denominatorIdx = fields.findIndex(f => f.name === field.metadata.denominator);return {- getNumerator: i => dataContainer.valueAt(i, numeratorIdx),- getDenominator: i => dataContainer.valueAt(i, denominatorIdx)+ getNumerator: i => fields[numeratorIdx].valueAccessor({index: i}),+ getDenominator: i => fields[denominatorIdx].valueAccessor({index: i})};}@@ -395,7 +395,7 @@ export const getValueAggrFunc = (aggregation: string,dataset: KeplerTableModel<any, any>): ((bin: Bin) => number) => {- const {dataContainer, fields} = dataset;+ const {fields} = dataset;// The passed-in field might not have all the fields set (e.g. valueAccessor)const datasetField = fields.find(@@ -408,7 +408,7 @@ export const getValueAggrFunc = (bin.indexes,getAgregationType(datasetField, aggregation),// @ts-expect-error can return {getNumerator, getDenominator}- getAggregationAccessor(datasetField, dataContainer, fields)+ getAggregationAccessor(datasetField, fields)): bin => bin.count;};diff --git a/test/node/utils/data-utils-test.js b/test/node/utils/data-utils-test.jsindex 82980dfde..339b792f1 100644--- a/test/node/utils/data-utils-test.js+++ b/test/node/utils/data-utils-test.js@@ -154,6 +154,15 @@ test('dataUtils -> getFormatter', t => {],assert: [4223, '4,200']},+ {+ input: [+ ',.2r',+ {+ type: ALL_FIELD_TYPES.integer+ }+ ],+ assert: [4223n, '4,200']+ },{input: ['01'],assert: [true, '1']diff --git a/test/node/utils/kepler-table-test.js b/test/node/utils/kepler-table-test.jsindex 10fba3e36..92b36ad84 100644--- a/test/node/utils/kepler-table-test.js+++ b/test/node/utils/kepler-table-test.js@@ -6,9 +6,10 @@ import moment from 'moment';import testData, {numericRangesCsv, testFields} from 'test/fixtures/test-csv-data';import {preciseRound, getFilterFunction} from '@kepler.gl/utils';-import {findPointFieldPairs} from '@kepler.gl/table';+import {findPointFieldPairs, KeplerTable} from '@kepler.gl/table';import {processCsvData} from '@kepler.gl/processors';-import {FILTER_TYPES} from '@kepler.gl/constants';+import {ALL_FIELD_TYPES, FILTER_TYPES} from '@kepler.gl/constants';+import * as arrow from 'apache-arrow';import {cmpFields} from '../../helpers/comparison-utils';import {createNewDataEntryMock} from '../../helpers/table-utils';@@ -415,3 +416,34 @@ test('KeplerTable -> findPointFieldPairs', t => {t.end();});++test('KeplerTable -> Int64 field accessor converts BigInt to number', async t => {+ const arrowTable = arrow.tableFromArrays({+ count: new BigInt64Array([1n, 9999n]),+ name: ['a', 'b']+ });+ const table = new KeplerTable({info: {id: 'int64'}, color: [0, 0, 0]});+ await table.importData({+ data: {+ fields: [+ {name: 'count', type: ALL_FIELD_TYPES.integer, analyzerType: 'INT'},+ {name: 'name', type: ALL_FIELD_TYPES.string, analyzerType: 'STRING'}+ ],+ cols: [arrowTable.getChildAt(0), arrowTable.getChildAt(1)],+ arrowTable+ }+ });++ t.equal(typeof table.dataContainer.valueAt(0, 0), 'bigint', 'valueAt stays raw BigInt');+ t.equal(table.dataContainer.valueAt(0, 0), 1n);+ t.equal(+ typeof table.fields[0].valueAccessor({index: 0}),+ 'number',+ 'Int64 valueAccessor returns a JS number'+ );+ t.equal(table.fields[0].valueAccessor({index: 0}), 1);+ t.equal(table.fields[0].valueAccessor({index: 1}), 9999);+ t.equal(table.fields[1].valueAccessor({index: 0}), 'a', 'non-Int64 accessors are unchanged');++ t.end();+});