Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

[feat] improvements to duckDB column type handling (#2970)

Igor Dykhta221b243c2e81
diff --git a/src/common-utils/src/data-type.ts b/src/common-utils/src/data-type.ts
index 39f450dcf..d736b0d82 100644
--- a/src/common-utils/src/data-type.ts
+++ b/src/common-utils/src/data-type.ts
@@ -2,7 +2,7 @@
// Copyright contributors to the kepler.gl project
import {Analyzer, DATA_TYPES as AnalyzerDATA_TYPES} from 'type-analyzer';
-import {RowData, Field} from '@kepler.gl/types';
+import {ArrowTableInterface, ApacheVectorInterface, RowData, Field} from '@kepler.gl/types';
import {ALL_FIELD_TYPES} from '@kepler.gl/constants';
import {console as globalConsole} from 'global/window';
import {range} from 'd3-array';
@@ -80,6 +80,54 @@ export function getSampleForTypeAnalyze({
return sample;
}
+/**
+ * Getting sample data for analyzing field type for Arrow tables.
+ * @param table Arrow table or an array of vectors.
+ * @param fields Field names.
+ * @param sampleCount Number of sample rows to get.
+ * @returns Sample rows.
+ */
+export function getSampleForTypeAnalyzeArrow(
+ table: ArrowTableInterface | ApacheVectorInterface[],
+ fields: string[],
+ sampleCount: number = 50
+): any[] {
+ const isTable = !Array.isArray(table);
+
+ const numRows = isTable ? table.numRows : table[0].length;
+ const getVector = isTable ? index => table.getChildAt(index) : index => table[index];
+
+ const total = Math.min(sampleCount, numRows);
+ const sample = range(0, total, 1).map(() => ({}));
+
+ if (numRows < 1) {
+ return [];
+ }
+
+ // collect sample data for each field
+ fields.forEach((field, fieldIdx) => {
+ let rowIndex = 0;
+ let sampleIndex = 0;
+
+ while (sampleIndex < total) {
+ if (rowIndex >= numRows) {
+ // if depleted data pool
+ sample[sampleIndex][field] = null;
+ sampleIndex++;
+ } else if (notNullorUndefined(getVector(fieldIdx)?.get(rowIndex))) {
+ const value = getVector(fieldIdx)?.get(rowIndex);
+ sample[sampleIndex][field] = typeof value === 'string' ? value.trim() : value;
+ sampleIndex++;
+ rowIndex++;
+ } else {
+ rowIndex++;
+ }
+ }
+ });
+
+ return sample;
+}
+
/**
* Convert type-analyzer output to kepler.gl field types
*
diff --git a/src/components/src/common/data-table/header-cell.tsx b/src/components/src/common/data-table/header-cell.tsx
index a249ec143..af356e44d 100644
--- a/src/components/src/common/data-table/header-cell.tsx
+++ b/src/components/src/common/data-table/header-cell.tsx
@@ -119,7 +119,7 @@ const HeaderCellFactory = (FieldToken: React.FC<FieldTokenProps>) => {
const firstCell = columnIndex === 0;
const isFormatted = Boolean(colMeta[column]?.displayFormat);
const formatLabels = isFormatted ? getFieldFormatLabels(colMeta[column].type) : [];
- const onSortTable = useCallback(() => sortTableColumn(column), [sortTableColumn, column]);
+ const onSortTable = useCallback(() => sortTableColumn?.(column), [sortTableColumn, column]);
const onToggleOptionMenu = useCallback(
() => toggleMoreOptions(column),
[toggleMoreOptions, column]
diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.ts
index e6670d92a..2ba76bf8d 100644
--- a/src/constants/src/default-settings.ts
+++ b/src/constants/src/default-settings.ts
@@ -1578,3 +1578,18 @@ export const SYNC_TIMELINE_MODES: Record<string, SyncTimelineMode> = {
start: 0,
end: 1
};
+
+export const GEOARROW_METADATA_KEY = 'ARROW:extension:name';
+
+/**
+ * Enum holding GeoArrow extension type names
+ */
+export enum GEOARROW_EXTENSIONS {
+ POINT = 'geoarrow.point',
+ LINESTRING = 'geoarrow.linestring',
+ POLYGON = 'geoarrow.polygon',
+ MULTIPOINT = 'geoarrow.multipoint',
+ MULTILINESTRING = 'geoarrow.multilinestring',
+ MULTIPOLYGON = 'geoarrow.multipolygon',
+ WKB = 'geoarrow.wkb'
+}
diff --git a/src/deckgl-arrow-layers/package.json b/src/deckgl-arrow-layers/package.json
index 2c78388b7..f1e3fef0c 100644
--- a/src/deckgl-arrow-layers/package.json
+++ b/src/deckgl-arrow-layers/package.json
@@ -31,6 +31,7 @@
],
"dependencies": {
"@geoarrow/geoarrow-js": "^0.3.0",
+ "@kepler.gl/constants": "^3.1.0",
"@math.gl/core": "^4.0.0",
"@math.gl/polygon": "^4.0.0",
"@math.gl/types": "^4.0.0",
diff --git a/src/deckgl-arrow-layers/src/constants.ts b/src/deckgl-arrow-layers/src/constants.ts
index 88422a4b4..4b5158741 100644
--- a/src/deckgl-arrow-layers/src/constants.ts
+++ b/src/deckgl-arrow-layers/src/constants.ts
@@ -5,17 +5,4 @@
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
-/**
- * Enum holding GeoArrow extension type names
- */
-export enum EXTENSION_NAME {
- POINT = 'geoarrow.point',
- LINESTRING = 'geoarrow.linestring',
- POLYGON = 'geoarrow.polygon',
- MULTIPOINT = 'geoarrow.multipoint',
- MULTILINESTRING = 'geoarrow.multilinestring',
- MULTIPOLYGON = 'geoarrow.multipolygon',
- WKB = 'geoarrow.wkb'
-}
-
export const DEFAULT_COLOR: [number, number, number, number] = [0, 0, 0, 255];
diff --git a/src/deckgl-arrow-layers/src/index.ts b/src/deckgl-arrow-layers/src/index.ts
index d5352f441..aea8bd713 100644
--- a/src/deckgl-arrow-layers/src/index.ts
+++ b/src/deckgl-arrow-layers/src/index.ts
@@ -1,8 +1,6 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-export {EXTENSION_NAME} from './constants';
-
export {GeoArrowScatterplotLayer} from './layers/geo-arrow-scatterplot-layer';
export {GeoArrowTextLayer} from './layers/geo-arrow-text-layer';
export {GeoArrowArcLayer} from './layers/geo-arrow-arc-layer';
diff --git a/src/deckgl-arrow-layers/src/layers/geo-arrow-scatterplot-layer.ts b/src/deckgl-arrow-layers/src/layers/geo-arrow-scatterplot-layer.ts
index 1f77ce8da..9b1dce3a2 100644
--- a/src/deckgl-arrow-layers/src/layers/geo-arrow-scatterplot-layer.ts
+++ b/src/deckgl-arrow-layers/src/layers/geo-arrow-scatterplot-layer.ts
@@ -18,6 +18,9 @@ import {ScatterplotLayer} from '@deck.gl/layers/typed';
import type {ScatterplotLayerProps} from '@deck.gl/layers/typed';
import * as arrow from 'apache-arrow';
import * as ga from '@geoarrow/geoarrow-js';
+
+import {GEOARROW_EXTENSIONS} from '@kepler.gl/constants';
+
import {
assignAccessor,
extractAccessorsFromProps,
@@ -26,7 +29,6 @@ import {
} from '../utils/utils';
import {GeoArrowExtraPickingProps, computeChunkOffsets, getPickingInfo} from '../utils/picking';
import {ColorAccessor, FloatAccessor, GeoArrowPickingInfo, ExtensionProps} from '../types';
-import {EXTENSION_NAME} from '../constants';
import {validateAccessors} from '../utils/validate';
/** All properties supported by GeoArrowScatterplotLayer */
@@ -121,12 +123,12 @@ export class GeoArrowScatterplotLayer<ExtraProps extends object = object> extend
throw new Error('getPosition should pass in an arrow Vector of Point or MultiPoint type');
} else {
- const pointVector = getGeometryVector(table, EXTENSION_NAME.POINT);
+ const pointVector = getGeometryVector(table, GEOARROW_EXTENSIONS.POINT);
if (pointVector !== null) {
return this._renderLayersPoint(pointVector);
}
- const multiPointVector = getGeometryVector(table, EXTENSION_NAME.MULTIPOINT);
+ const multiPointVector = getGeometryVector(table, GEOARROW_EXTENSIONS.MULTIPOINT);
if (multiPointVector !== null) {
return this._renderLayersMultiPoint(multiPointVector);
}
diff --git a/src/deckgl-arrow-layers/src/layers/geo-arrow-text-layer.ts b/src/deckgl-arrow-layers/src/layers/geo-arrow-text-layer.ts
index 935695546..d8b0faa2d 100644
--- a/src/deckgl-arrow-layers/src/layers/geo-arrow-text-layer.ts
+++ b/src/deckgl-arrow-layers/src/layers/geo-arrow-text-layer.ts
@@ -18,6 +18,9 @@ import {TextLayer} from '@deck.gl/layers/typed';
import type {TextLayerProps} from '@deck.gl/layers';
import * as arrow from 'apache-arrow';
import * as ga from '@geoarrow/geoarrow-js';
+
+import {GEOARROW_EXTENSIONS} from '@kepler.gl/constants';
+
import {
assignAccessor,
expandArrayToCoords,
@@ -26,7 +29,6 @@ import {
} from '../utils/utils';
import {GeoArrowExtraPickingProps, computeChunkOffsets, getPickingInfo} from '../utils/picking';
import {ColorAccessor, FloatAccessor, GeoArrowPickingInfo, ExtensionProps} from '../types';
-import {EXTENSION_NAME} from '../constants';
import {validateAccessors} from '../utils/validate';
/** All properties supported by GeoArrowTextLayer */
@@ -167,7 +169,7 @@ export class GeoArrowTextLayer<ExtraProps extends object = object> extends Compo
throw new Error('getPosition should pass in an arrow Vector of Point type');
} else {
- const pointVector = getGeometryVector(table, EXTENSION_NAME.POINT);
+ const pointVector = getGeometryVector(table, GEOARROW_EXTENSIONS.POINT);
if (pointVector !== null) {
return this._renderLayersPoint(pointVector);
}
diff --git a/src/duckdb/src/components/preview-data-panel.tsx b/src/duckdb/src/components/preview-data-panel.tsx
index 8d12e5061..d0529c958 100644
--- a/src/duckdb/src/components/preview-data-panel.tsx
+++ b/src/duckdb/src/components/preview-data-panel.tsx
@@ -1,13 +1,13 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
+import * as arrow from 'apache-arrow';
import React, {useCallback, useMemo, useState, CSSProperties} from 'react';
+import {withTheme} from 'styled-components';
import {DataTable, renderedSize} from '@kepler.gl/components';
-import {parseFieldValue, createDataContainer} from '@kepler.gl/utils';
import {arrowSchemaToFields} from '@kepler.gl/processors';
-import {DataForm} from '@kepler.gl/utils';
-import {withTheme} from 'styled-components';
+import {parseFieldValue, createDataContainer, DataForm} from '@kepler.gl/utils';
type BaseComponentProps = {
className?: string;
@@ -39,14 +39,19 @@ export type DataTableStyle = {
optionsButton?: number;
};
+export type QueryResult = {
+ table: arrow.Table;
+ tableDuckDBTypes: Record<string, string>;
+};
+
export type PreviewDataPanelProps = BaseComponentProps & {
- result: any;
+ result: QueryResult;
rowsToCalculatePreview?: number;
theme?: any;
setColumnDisplayFormat?: (formats: {[key: string]: string}) => void;
defaultPinnedColumns?: string[];
dataTableStyle: DataTableStyle;
- onAddResultToMap: (result: any) => void;
+ onAddResultToMap: (result: QueryResult) => void;
};
const PreviewDataPanelWOTheme: React.FC<PreviewDataPanelProps> = ({
@@ -57,9 +62,12 @@ const PreviewDataPanelWOTheme: React.FC<PreviewDataPanelProps> = ({
theme
}) => {
const [pinnedColumns, setPinnedColumns] = useState<string[]>(defaultPinnedColumns);
- const fields = useMemo(() => arrowSchemaToFields(result.schema), [result.schema]);
+ const fields = useMemo(
+ () => arrowSchemaToFields(result.table, result.tableDuckDBTypes),
+ [result]
+ );
const dataContainer = useMemo(() => {
- const cols = [...Array(result.numCols).keys()].map(i => result.getChildAt(i));
+ const cols = [...Array(result.table.numCols).keys()].map(i => result.table.getChildAt(i));
const dataContainer = createDataContainer(cols, {
fields,
diff --git a/src/duckdb/src/components/schema-panel.tsx b/src/duckdb/src/components/schema-panel.tsx
index d80241210..0c493490d 100644
--- a/src/duckdb/src/components/schema-panel.tsx
+++ b/src/duckdb/src/components/schema-panel.tsx
@@ -4,11 +4,14 @@
import React, {useCallback, useEffect, useState} from 'react';
import {useSelector} from 'react-redux';
import styled from 'styled-components';
-import {arrowDataTypeToFieldType} from '@kepler.gl/utils';
-import {ALL_FIELD_TYPES} from '@kepler.gl/constants';
+import {AsyncDuckDBConnection} from '@duckdb/duckdb-wasm';
+
+import {arrowSchemaToFields} from '@kepler.gl/processors';
import {VisState} from '@kepler.gl/schemas';
+
import {Tree, DatasetNode, ColumnNode, TreeNodeData} from './tree';
import {getDuckDB} from '../init';
+import {getDuckDBColumnTypes, getDuckDBColumnTypesMap} from '../table/duckdb-table-utils';
// TODO note that demo state is available in demo-app, but not when add modules to dependencies in a custom map
type State = {
@@ -28,26 +31,26 @@ const StyledSchemaPanel = styled.div`
font-family: ${props => props.theme.fontFamily};
`;
-async function getColumnSchema(c, name) {
- const columnResult = await c.query(`Select * from '${name}' LIMIT 1;`);
+async function getColumnSchema(connection: AsyncDuckDBConnection, tableName: string) {
+ const columnResult = await connection.query(`Select * from '${tableName}' LIMIT 1;`);
+
+ const columnDescribe = await getDuckDBColumnTypes(connection, tableName);
+ const keplerFields = arrowSchemaToFields(columnResult, getDuckDBColumnTypesMap(columnDescribe));
return {
- key: name,
+ key: tableName,
object: {
type: 'dataset',
- tableName: name
+ tableName: tableName
},
- children: columnResult.schema.fields.map(field => {
- const isGeoArrowColumn = field.metadata.get('ARROW:extension:name')?.startsWith('geoarrow');
+ children: columnResult.schema.fields.map((field, fieldIndex) => {
return {
key: field.name,
object: {
type: 'column',
name: field.name,
arrowType: field.type,
- fieldType: isGeoArrowColumn
- ? ALL_FIELD_TYPES.geoarrow
- : arrowDataTypeToFieldType(field.type)
+ fieldType: keplerFields[fieldIndex].type
}
};
})
diff --git a/src/duckdb/src/components/sql-panel.tsx b/src/duckdb/src/components/sql-panel.tsx
index aecd41c8f..4a2788851 100644
--- a/src/duckdb/src/components/sql-panel.tsx
+++ b/src/duckdb/src/components/sql-panel.tsx
@@ -6,17 +6,28 @@ import React, {useCallback, useState, useEffect} from 'react';
import {useDispatch} from 'react-redux';
import styled from 'styled-components';
import {Panel, PanelGroup, PanelResizeHandle} from 'react-resizable-panels';
-import MonacoEditor from './monaco-editor';
-import {SchemaPanel} from './schema-panel';
-import {PreviewDataPanel} from './preview-data-panel';
-import {getDuckDB} from '../init';
-import {Button, IconButton, Tooltip} from '@kepler.gl/components';
-import {generateHashId} from '@kepler.gl/common-utils';
+
import {addDataToMap} from '@kepler.gl/actions';
-import {Icons, LoadingSpinner} from '@kepler.gl/components';
+import {generateHashId} from '@kepler.gl/common-utils';
+import {Button, IconButton, Icons, LoadingSpinner, Tooltip} from '@kepler.gl/components';
+import {arrowSchemaToFields} from '@kepler.gl/processors';
import {sidePanelBg, panelBorderColor} from '@kepler.gl/styles';
import {isAppleDevice} from '@kepler.gl/utils';
-import {arrowSchemaToFields} from '@kepler.gl/processors';
+
+import MonacoEditor from './monaco-editor';
+import {SchemaPanel} from './schema-panel';
+import {PreviewDataPanel, QueryResult} from './preview-data-panel';
+import {getDuckDB} from '../init';
+import {
+ constructST_asWKBQuery,
+ getDuckDBColumnTypes,
+ getDuckDBColumnTypesMap,
+ getGeometryColumns,
+ setGeoArrowWKBExtension,
+ splitSqlStatements,
+ checkIsSelectQuery,
+ removeSQLComments
+} from '../table/duckdb-table-utils';
const StyledSqlPanel = styled.div`
display: flex;
@@ -125,7 +136,7 @@ export const SqlPanel: React.FC<SqlPanelProps> = ({initialSql = ''}) => {
const params = new URLSearchParams(window.location.search);
return params.get('sql') || initialSql;
});
- const [result, setResult] = useState<null | arrow.Table>(null);
+ const [result, setResult] = useState<null | QueryResult>(null);
const [error, setError] = useState<Error | null>(null);
const [counter, setCounter] = useState(0);
const [tableSchema, setTableSchema] = useState([]);
@@ -146,7 +157,8 @@ export const SqlPanel: React.FC<SqlPanelProps> = ({initialSql = ''}) => {
const runQuery = useCallback(async () => {
setIsRunning(true);
try {
- if (!sql?.trim()) {
+ const adjustedQuery = sql ? removeSQLComments(sql) : null;
+ if (!adjustedQuery) {
setError(new Error('Query is empty'));
return;
}
@@ -154,8 +166,45 @@ export const SqlPanel: React.FC<SqlPanelProps> = ({initialSql = ''}) => {
const db = await getDuckDB();
const connection = await db.connect();
- const arrowResult = await connection.query(sql);
- setResult(arrowResult);
+ // TODO find a cheap way to get DuckDb types with a single query to a remote resource - temp table? cte?
+ const tempTableName = 'temp_keplergl_table';
+
+ // remove comments
+ const sqlStatements = splitSqlStatements(adjustedQuery);
+
+ let arrowResult: arrow.Table | null = null;
+ let tableDuckDBTypes = {};
+
+ for (const statement of sqlStatements) {
+ const isLastQuery = statement === sqlStatements[sqlStatements.length - 1];
+ if (isLastQuery && (await checkIsSelectQuery(connection, statement))) {
+ // 1) create temp table from the original query.
+ await connection.query(`CREATE OR REPLACE TABLE '${tempTableName}' AS ${statement}`);
+
+ // 2) query duckdb types and detect candidate columns for ST_asWKB transform.
+ const duckDbColumns = await getDuckDBColumnTypes(connection, tempTableName);
+ tableDuckDBTypes = getDuckDBColumnTypesMap(duckDbColumns);
+ const columnsToConvertToWKB = getGeometryColumns(duckDbColumns);
+
+ // 3) query GEOMETRY columns as WKB.
+ const adjustedQuery = constructST_asWKBQuery(tempTableName, columnsToConvertToWKB);
+ arrowResult = await connection.query(adjustedQuery);
+
+ // 4) set geoarrow extension for the arrow table as DuckDB doesn't support the geoarrow extension.
+ setGeoArrowWKBExtension(arrowResult, duckDbColumns);
+
+ // 5) remove temp table
+ await connection.query(`DROP TABLE ${tempTableName};`);
+ } else {
+ await connection.query(statement);
+ }
+ }
+
+ if (!arrowResult) {
+ throw new Error('no result');
+ }
+
+ setResult({table: arrowResult, tableDuckDBTypes});
setError(null);
connection.close();
@@ -176,13 +225,13 @@ export const SqlPanel: React.FC<SqlPanelProps> = ({initialSql = ''}) => {
const onAddResultToMap = useCallback(() => {
if (!result) return;
- const keplerFields = arrowSchemaToFields(result.schema);
+ const keplerFields = arrowSchemaToFields(result.table, result.tableDuckDBTypes);
const datasetToAdd = {
data: {
fields: keplerFields,
// TODO type AddDataToMapPayload -> rows -> + arrow.Table
- rows: result as any
+ rows: result.table as any
},
info: {
id: generateHashId(),
@@ -250,7 +299,7 @@ export const SqlPanel: React.FC<SqlPanelProps> = ({initialSql = ''}) => {
<Button secondary onClick={onAddResultToMap}>
Add to Map
</Button>
- <div>{result.numRows} rows</div>
+ <div>{result.table.numRows} rows</div>
</StyledResultActions>
<PreviewDataPanel
result={result}
diff --git a/src/duckdb/src/table/duckdb-table-utils.ts b/src/duckdb/src/table/duckdb-table-utils.ts
index aa6a11226..a39dc9b83 100644
--- a/src/duckdb/src/table/duckdb-table-utils.ts
+++ b/src/duckdb/src/table/duckdb-table-utils.ts
@@ -7,9 +7,149 @@
// Copied from loaders.gl/geoarrow
-// TODO: Remove once Kepler.gl is upgraded to loaders.gl 4.4+
+// TODO: Remove isGeoArrow* once Kepler.gl is upgraded to loaders.gl 4.4+
+import * as arrow from 'apache-arrow';
import {DataType} from 'apache-arrow/type';
+import {AsyncDuckDBConnection} from '@duckdb/duckdb-wasm';
+
+import {GEOARROW_EXTENSIONS, GEOARROW_METADATA_KEY} from '@kepler.gl/constants';
+import {ProtoDatasetField} from '@kepler.gl/types';
+
+export type DuckDBColumnDesc = {name: string; type: string};
+
+/**
+ * Queries a DuckDB table for the schema description.
+ * @param connection An active DuckDB connection.
+ * @param tableName A name of DuckDB table to query.
+ * @returns An array of column names and DuckDB types.
+ */
+export async function getDuckDBColumnTypes(
+ connection: AsyncDuckDBConnection,
+ tableName: string
+): Promise<DuckDBColumnDesc[]> {
+ const resDescribe = await connection.query(`DESCRIBE "${tableName}";`);
+
+ const duckDbTypes: DuckDBColumnDesc[] = [];
+ const numRows = resDescribe.numRows;
+ for (let i = 0; i < numRows; ++i) {
+ const columnName = resDescribe.getChildAt(0)?.get(i);
+ const columnType = resDescribe.getChildAt(1)?.get(i);
+
+ duckDbTypes.push({
+ name: columnName,
+ type: columnType
+ });
+ }
+
+ return duckDbTypes;
+}
+
+/**
+ * Generates a mapping of column names to their corresponding DuckDB data types.
+ * @param columns An array of column descriptions from DuckDB. Check getDuckDBColumnTypes.
+ * @returns A record where keys are column names and values are their data types.
+ */
+export function getDuckDBColumnTypesMap(columns: DuckDBColumnDesc[]) {
+ return columns.reduce((acc, value) => {
+ acc[value.name] = value.type;
+ return acc;
+ }, {} as Record<string, string>);
+}
+
+/**
+ * Constructs an SQL query to select all columns from a given table,
+ * converting specified columns to Well-Known Binary (WKB) format using ST_AsWKB.
+ * @param tableName The name of the table from which to select data.
+ * @param columnsToConvertToWKB An array of column names that should be converted to WKB format.
+ * @returns The constructed SQL query.
+ */
+export function constructST_asWKBQuery(tableName: string, columnsToConvertToWKB: string[]): string {
+ const exclude =
+ columnsToConvertToWKB.length > 0 ? `EXCLUDE ${columnsToConvertToWKB.join(', ')}` : '';
+ const asWKB =
+ columnsToConvertToWKB.length > 0
+ ? ', ' + columnsToConvertToWKB.map(column => `ST_AsWKB(${column}) as ${column}`).join(', ')
+ : '';
+ return `SELECT * ${exclude} ${asWKB} FROM '${tableName}';`;
+}
+
+/**
+ * Finds the names of columns that have a GEOMETRY type.
+ * @param columns An array of column descriptors from a DuckDB table.
+ * @returns An array of column names that are of type GEOMETRY.
+ */
+export function getGeometryColumns(columns: DuckDBColumnDesc[]): string[] {
+ return columns.filter(column => column.type === 'GEOMETRY').map(column => column.name);
+}
+
+/**
+ * Sets the GeoArrow WKB extension metadata for columns of type GEOMETRY in an Arrow table.
+ * @param table The Apache Arrow table whose schema fields will be modified.
+ * @param columns An array of column descriptors from a DuckDB table.
+ */
+export function setGeoArrowWKBExtension(table: arrow.Table, columns: DuckDBColumnDesc[]) {
+ table.schema.fields.forEach(field => {
+ const info = columns.find(t => t.name === field.name);
+ if (info?.type === 'GEOMETRY') {
+ field.metadata.set(GEOARROW_METADATA_KEY, GEOARROW_EXTENSIONS.WKB);
+ }
+ });
+}
+
+/**
+ * Creates an arrow table from an array of arrow vectors and fields.
+ * @param columns An array of arrow vectors.
+ * @param fields An array of fields per arrow vector.
+ * @param arrowSchema Optional arrow table schema when available.
+ * @returns An arrow table.
+ */
+export const restoreArrowTable = (
+ columns: arrow.Vector[],
+ fields: ProtoDatasetField[],
+ arrowSchema?: arrow.Schema
+) => {
+ const creaOpts = {};
+ fields.map((field, index) => {
+ creaOpts[field.name] = columns[index];
+ });
+
+ return arrowSchema ? new arrow.Table(arrowSchema, creaOpts) : new arrow.Table(creaOpts);
+};
+
+/**
+ * DuckDb throws when geoarrow extensions are present in metadata.
+ * @param table An arrow table to clear from extensions.
+ * @returns A map of removed per field geoarrow extensions.
+ */
+export const removeUnsupportedExtensions = (table: arrow.Table): Record<string, string> => {
+ const removedMetadata: Record<string, string> = {};
+ table.schema.fields.forEach(field => {
+ const extension = field.metadata.get(GEOARROW_METADATA_KEY);
+ if (extension?.startsWith('geoarrow')) {
+ removedMetadata[field.name] = extension;
+ field.metadata.delete(GEOARROW_METADATA_KEY);
+ }
+ });
+ return removedMetadata;
+};
+
+/**
+ * Restore removed metadata extensions after a call to removeUnsupportedExtensions.
+ * @param table An arrow table to restore geoarrow extensions.
+ * @param removedExtensions A map of per field geoarrow extensions to restore.
+ */
+export const restoreUnsupportedExtensions = (
+ table: arrow.Table,
+ removedExtensions: Record<string, string>
+) => {
+ table.schema.fields.forEach(field => {
+ const extension = removedExtensions[field.name];
+ if (extension) {
+ field.metadata.set(GEOARROW_METADATA_KEY, extension);
+ }
+ });
+};
/** Checks whether the given Apache Arrow JS type is a Point data type */
export function isGeoArrowPoint(type: DataType) {
@@ -104,3 +244,162 @@ export function isGeoArrowMultiPolygon(type: DataType) {
return true;
}
+
+/**
+ * Checks if the given SQL query is a SELECT query by using the EXPLAIN command.
+ * @param connection The DuckDB connection instance.
+ * @param query The SQL query to check.
+ * @returns Resolves to `true` if the query is a SELECT statement, otherwise `false`.
+ */
+export async function checkIsSelectQuery(
+ connection: AsyncDuckDBConnection,
+ query: string
+): Promise<boolean> {
+ try {
+ const result = await connection.query(`EXPLAIN (${query})`);
+ return result.numRows > 0;
+ } catch (error) {
+ return false;
+ }
+}
+
+/**
+ * Split a string with potentially multiple SQL queries (separated as usual by ';') into an array of queries.
+ * This implementation:
+ * - Handles single and double quoted strings with proper escaping
+ * - Ignores semicolons in line comments (--) and block comments (slash asterisk)
+ * - Trims whitespace from queries
+ * - Handles SQL-style escaped quotes ('' inside strings)
+ * - Returns only non-empty queries
+ * @param input A string with potentially multiple SQL queries.
+ * @returns An array of queries.
+ */
+export function splitSqlStatements(input: string): string[] {
+ const queries: string[] = [];
+ let currentQuery = '';
+ let inSingleQuote = false;
+ let inDoubleQuote = false;
+ let inLineComment = false;
+ let inBlockComment = false;
+
+ for (let i = 0; i < input.length; i++) {
+ const char = input[i];
+
+ if (inLineComment) {
+ currentQuery += char;
+ if (char === '\n') {
+ inLineComment = false;
+ }
+ continue;
+ }
+
+ if (inBlockComment) {
+ currentQuery += char;
+ if (char === '*' && input[i + 1] === '/') {
+ inBlockComment = false;
+ currentQuery += input[++i]; // Consume '/'
+ }
+ continue;
+ }
+
+ if (inSingleQuote) {
+ currentQuery += char;
+ if (char === "'") {
+ // Handle escaped single quotes in SQL
+ if (i + 1 < input.length && input[i + 1] === "'") {
+ currentQuery += input[++i];
+ } else {
+ inSingleQuote = false;
+ }
+ }
+ continue;
+ }
+
+ if (inDoubleQuote) {
+ currentQuery += char;
+ if (char === '"') {
+ // Handle escaped double quotes
+ if (i + 1 < input.length && input[i + 1] === '"') {
+ currentQuery += input[++i];
+ } else {
+ inDoubleQuote = false;
+ }
+ }
+ continue;
+ }
+
+ // Check for comment starts
+ if (char === '-' && input[i + 1] === '-') {
+ inLineComment = true;
+ currentQuery += char + input[++i];
+ continue;
+ }
+
+ if (char === '/' && input[i + 1] === '*') {
+ inBlockComment = true;
+ currentQuery += char + input[++i];
+ continue;
+ }
+
+ // Check for quote starts
+ if (char === "'") {
+ inSingleQuote = true;
+ currentQuery += char;
+ continue;
+ }
+
+ if (char === '"') {
+ inDoubleQuote = true;
+ currentQuery += char;
+ continue;
+ }
+
+ // Handle query separator
+ if (char === ';') {
+ const trimmed = currentQuery.trim();
+ if (trimmed.length > 0) {
+ queries.push(trimmed);
+ }
+ currentQuery = '';
+ continue;
+ }
+
+ currentQuery += char;
+ }
+
+ // Add the final query
+ const trimmed = currentQuery.trim();
+ if (trimmed.length > 0) {
+ queries.push(trimmed);
+ }
+
+ return queries;
+}
+
+/**
+ * Removes SQL comments from a given SQL string.
+ * @param sql The SQL query string from which comments should be removed.
+ * @returns The cleaned SQL string without comments.
+ */
+export function removeSQLComments(sql: string): string {
+ // Remove multi-line comments (/* ... */)
+ sql = sql.replace(/\/\*[\s\S]*?\*\//g, '');
+ // Remove single-line comments (-- ...)
+ sql = sql.replace(/--.*$/gm, '');
+ return sql.trim();
+}
+
+/**
+ * Drops a table if it exists in the DuckDB database.
+ * @param connection The DuckDB connection instance.
+ * @param tableName The name of the table to drop.
+ * @returns A promise that resolves when the operation is complete.
+ * @throws Logs an error if the table drop operation fails.
+ */
+export const dropTableIfExists = async (connection: AsyncDuckDBConnection, tableName: string) => {
+ try {
+ await connection.query(`DROP TABLE IF EXISTS "${tableName}";`);
+ } catch (error) {
+ console.error('Dropping table failed', tableName, error);
+ }
+};
diff --git a/src/duckdb/src/table/duckdb-table.ts b/src/duckdb/src/table/duckdb-table.ts
index ab1325fa4..7ba32204a 100644
--- a/src/duckdb/src/table/duckdb-table.ts
+++ b/src/duckdb/src/table/duckdb-table.ts
@@ -4,9 +4,14 @@
import * as arrow from 'apache-arrow';
import {AsyncDuckDB, AsyncDuckDBConnection} from '@duckdb/duckdb-wasm';
-import {DatasetType, DATASET_FORMATS} from '@kepler.gl/constants';
+import {
+ DatasetType,
+ DATASET_FORMATS,
+ GEOARROW_EXTENSIONS,
+ GEOARROW_METADATA_KEY
+} from '@kepler.gl/constants';
import {KeplerTable} from '@kepler.gl/table';
-import {Field, ProtoDatasetField} from '@kepler.gl/types';
+import {Field} from '@kepler.gl/types';
import {
arrowSchemaToFields,
isArrowData,
@@ -33,6 +38,17 @@ import {
isGeoArrowMultiPolygon
} from './duckdb-table-utils';
+import {
+ constructST_asWKBQuery,
+ dropTableIfExists,
+ getDuckDBColumnTypes,
+ getDuckDBColumnTypesMap,
+ getGeometryColumns,
+ removeUnsupportedExtensions,
+ restoreArrowTable,
+ restoreUnsupportedExtensions
+} from '../table/duckdb-table-utils';
+
// TODO use files from disk or url directly, without parsing by loaders and then ingection into DeckDb
/**
@@ -52,47 +68,24 @@ const KEPLER_GEOM_FROM_GEOJSON_COLUMN = '_geojson';
* Names of columns that most likely contain binary wkb geometry
*/
const SUGGESTED_GEOM_COLUMNS = {
- [KEPLER_GEOM_FROM_GEOJSON_COLUMN]: true,
- [DUCKDB_GEOM_COLUMN]: true,
- geometry: true
+ [KEPLER_GEOM_FROM_GEOJSON_COLUMN]: GEOARROW_EXTENSIONS.WKB,
+ [DUCKDB_GEOM_COLUMN]: GEOARROW_EXTENSIONS.WKB,
+ geometry: GEOARROW_EXTENSIONS.WKB
};
type ImportDataToDuckProps = {
- data: ProcessorResult;
+ data: ProcessorResult & {arrowSchema: arrow.Schema};
db: AsyncDuckDB;
c: AsyncDuckDBConnection;
};
type ImportDataToDuckResult = {
- // DuckDb drops geoarrow metadata, so try to preserve someting
- addWKBMetadata?: Record<string, boolean>;
+ // DuckDb drops geoarrow metadata, so try to preserve and then restore the extension name
+ geoarrowMetadata?: Record<string, string>;
// Use fields from arrow table even if fields are provided
useNewFields?: boolean;
};
-/**
- * Creates an arrow table from arrow vectors and fields.
- * @param columns An array of arrow vectors.
- * @param fields An array of fields per arrow vector.
- * @returns An arrow table.
- */
-// TODO: consider using original drag&dropped arrow table, as it could contain extra metadata, not passed to the fields.
-const restoreArrowTable = (columns: arrow.Vector[], fields: ProtoDatasetField[]) => {
- const creaOpts = {};
- fields.map((field, index) => {
- creaOpts[field.name] = columns[index];
- });
- return new arrow.Table(creaOpts);
-};
-
-const dropIfTableExists = async (c: AsyncDuckDBConnection, tableName: string) => {
- try {
- await c.query(`DROP TABLE IF EXISTS "${tableName}";`);
- } catch (error) {
- console.error('Dropping table failed', tableName, error);
- }
-};
-
export class KeplerGlDuckDbTable extends KeplerTable {
declare readonly id: string;
declare label: string;
@@ -157,18 +150,23 @@ export class KeplerGlDuckDbTable extends KeplerTable {
}
return {
- addWKBMetadata: {[KEPLER_GEOM_FROM_GEOJSON_COLUMN]: true}
+ // _geojson column is created from geometry with keep_wkb flag and contains valid WKB data.
+ geoarrowMetadata: {[KEPLER_GEOM_FROM_GEOJSON_COLUMN]: GEOARROW_EXTENSIONS.WKB}
};
}
async importArrowData({data, db, c}: ImportDataToDuckProps): Promise<ImportDataToDuckResult> {
+ let adjustedMetadata = {};
try {
// 1) data.rows contains an arrow table created by Add to Map data from DuckDb query.
// 2) arrow table is in cols & fields when a file is dragged & dropped into Add Data To Map dialog.
const arrowTable =
data.rows instanceof arrow.Table
? data.rows
- : restoreArrowTable(data.cols || [], data.fields);
+ : restoreArrowTable(data.cols || [], data.fields, data.arrowSchema);
+
+ // remove unsupported extensions from an arrow table that throw exceptions in DuckDB.
+ adjustedMetadata = removeUnsupportedExtensions(arrowTable);
const setupSql = `
install spatial;
@@ -176,6 +174,9 @@ export class KeplerGlDuckDbTable extends KeplerTable {
`;
await c.query(setupSql);
await c.insertArrowTable(arrowTable, {name: this.label});
+
+ // restore unsupported extensions that throw exceptions in DuckDb
+ restoreUnsupportedExtensions(arrowTable, adjustedMetadata);
} catch (error) {
// Known issues:
// 1) Arrow Type with extension name: geoarrow.point and format: +w:2 is not currently supported in DuckDB.
@@ -183,8 +184,8 @@ export class KeplerGlDuckDbTable extends KeplerTable {
}
return {
- addWKBMetadata: {...SUGGESTED_GEOM_COLUMNS},
- // use metadata from arrow table
+ geoarrowMetadata: {...SUGGESTED_GEOM_COLUMNS, ...adjustedMetadata},
+ // use fields generated from the created arrow table
useNewFields: true
};
}
@@ -199,7 +200,7 @@ export class KeplerGlDuckDbTable extends KeplerTable {
const c = await db.connect();
const tableName = this.label;
- await dropIfTableExists(c, tableName);
+ await dropTableIfExists(c, tableName);
let format = this.metadata.format;
if (!format) {
@@ -228,27 +229,26 @@ export class KeplerGlDuckDbTable extends KeplerTable {
let cols: arrow.Vector[] = [];
try {
- const {addWKBMetadata = {}, useNewFields = false} = importDetails || {};
+ const {geoarrowMetadata = {}, useNewFields = false} = importDetails || {};
- // Try to figure out whether geometry should be transformed by ST_AsWKB
- // TODO if canCastST_asWKB contains any keys then add ST_AsWKB to the following query
- const canCastST_asWKB = await tryST_AsWKB({tableName, c});
+ const duckDbColumns = await getDuckDBColumnTypes(c, tableName);
+ const tableDuckDBTypes = getDuckDBColumnTypesMap(duckDbColumns);
+ const columnsToConvertToWKB = getGeometryColumns(duckDbColumns);
+ const adjustedQuery = constructST_asWKBQuery(tableName, columnsToConvertToWKB);
+ const arrowResult = await c.query(adjustedQuery);
- const getArrowQuery = `SELECT * FROM '${tableName}';`;
- const arrowResult = await c.query(getArrowQuery);
+ // TODO if format is an arrow table then just use the original one, instead of the new table from the query?
- restoreGeoarrowMetadata(arrowResult, canCastST_asWKB, addWKBMetadata);
+ restoreGeoarrowMetadata(arrowResult, geoarrowMetadata);
fields = useNewFields
- ? arrowSchemaToFields(arrowResult.schema)
- : data.fields ?? arrowSchemaToFields(arrowResult.schema);
+ ? arrowSchemaToFields(arrowResult, tableDuckDBTypes)
+ : data.fields ?? arrowSchemaToFields(arrowResult, tableDuckDBTypes);
cols = [...Array(arrowResult.numCols).keys()]
.map(i => arrowResult.getChildAt(i))
.filter(col => col) as arrow.Vector[];
} catch (error) {
- // Known issues:
- // 1) ST_AsWKB binder error, no type match
- console.error('DuckDb table: binary geometry column to wkb', error);
+ console.error('DuckDB table: createTableAndGetArrow', error);
}
await c.close();
@@ -285,7 +285,6 @@ export class KeplerGlDuckDbTable extends KeplerTable {
let format;
if (inputFormat === DATASET_FORMATS.arrow || isArrowData(data)) {
format = DATASET_FORMATS.arrow;
- // TODO injest arrow files from disk without loaders
processor = processArrowBatches;
} else if (inputFormat === DATASET_FORMATS.keplergl || isKeplerGlMap(data)) {
format = DATASET_FORMATS.keplergl;
@@ -310,58 +309,27 @@ export class KeplerGlDuckDbTable extends KeplerTable {
* Try to restore geoarrow metadata lost during DuckDb ingestion.
* Note that this function can generate wrong geometry types.
* @param arrowTable Arrow table to update.
- * @param canCastST_asWKB A map with fields that are likely in DeckDB's internal WBK format.
- * @param addWKBMetadata A map with field names that usually used to store WKB geometry.
+ * @param geoarrowMetadata A map with field names that usually used to store geoarrow geometry.
*/
const restoreGeoarrowMetadata = async (
arrowTable: arrow.Table,
- canCastST_asWKB: Record<string, boolean>,
- addWKBMetadata: Record<string, boolean>
+ geoarrowMetadata: Record<string, string>
) => {
arrowTable.schema.fields.forEach(f => {
- if (arrow.DataType.isBinary(f.type) && (addWKBMetadata[f.name] || canCastST_asWKB[f.name])) {
- f.metadata.set('ARROW:extension:name', 'geoarrow.wkb');
+ if (arrow.DataType.isBinary(f.type) && geoarrowMetadata[f.name]) {
+ f.metadata.set(GEOARROW_METADATA_KEY, geoarrowMetadata[f.name]);
} else if (isGeoArrowPoint(f.type)) {
- f.metadata.set('ARROW:extension:name', 'geoarrow.point');
+ f.metadata.set(GEOARROW_METADATA_KEY, GEOARROW_EXTENSIONS.POINT);
} else if (isGeoArrowLineString(f.type)) {
- f.metadata.set('ARROW:extension:name', 'geoarrow.linestring');
+ f.metadata.set(GEOARROW_METADATA_KEY, GEOARROW_EXTENSIONS.LINESTRING);
} else if (isGeoArrowPolygon(f.type)) {
- f.metadata.set('ARROW:extension:name', 'geoarrow.polygon');
+ f.metadata.set(GEOARROW_METADATA_KEY, GEOARROW_EXTENSIONS.POLYGON);
} else if (isGeoArrowMultiPoint(f.type)) {
- f.metadata.set('ARROW:extension:name', 'geoarrow.multipoint');
+ f.metadata.set(GEOARROW_METADATA_KEY, GEOARROW_EXTENSIONS.MULTIPOINT);
} else if (isGeoArrowMultiLineString(f.type)) {
- f.metadata.set('ARROW:extension:name', 'geoarrow.multilinestring');
+ f.metadata.set(GEOARROW_METADATA_KEY, GEOARROW_EXTENSIONS.MULTILINESTRING);
} else if (isGeoArrowMultiPolygon(f.type)) {
- f.metadata.set('ARROW:extension:name', 'geoarrow.multipolygon');
+ f.metadata.set(GEOARROW_METADATA_KEY, GEOARROW_EXTENSIONS.MULTIPOLYGON);
}
});
};
-
-/**
- * For all binary columns tries to transform geometry from DuckDB's internal format into proper WKB.
- * @param props
- * @returns A map of fields that should be transformed to valid WKB.
- */
-const tryST_AsWKB = async (props: {tableName: string; c: AsyncDuckDBConnection}) => {
- const {c, tableName} = props;
-
- const resultWithSchema = await c.query(`
- SELECT * FROM '${tableName}' LIMIT 0;
- `);
- const binaryColumns = resultWithSchema.schema.fields.filter(f => arrow.DataType.isBinary(f.type));
-
- const canCastST_asWKB: Record<string, boolean> = {};
- for (const column of binaryColumns) {
- try {
- const columnName = column.name;
- const query = `SELECT * EXCLUDE ${columnName}, ST_AsWKB(${columnName}) as ${columnName} FROM '${tableName}' LIMIT 1;`;
- await c.query(query);
-
- canCastST_asWKB[column.name] = true;
- } catch (error) {
- canCastST_asWKB[column.name] = false;
- }
- }
-
- return canCastST_asWKB;
-};
diff --git a/src/layers/src/layer-utils.ts b/src/layers/src/layer-utils.ts
index f1f89736c..6697e7701 100644
--- a/src/layers/src/layer-utils.ts
+++ b/src/layers/src/layer-utils.ts
@@ -5,6 +5,7 @@ import * as arrow from 'apache-arrow';
import {Feature, BBox} from 'geojson';
import {getGeoMetadata} from '@loaders.gl/gis';
+import {GEOARROW_EXTENSIONS, GEOARROW_METADATA_KEY} from '@kepler.gl/constants';
import {KeplerTable} from '@kepler.gl/table';
import {
Field,
@@ -22,7 +23,6 @@ import {
BinaryGeometriesFromArrowOptions,
updateBoundsFromGeoArrowSamples
} from '@loaders.gl/arrow';
-import {EXTENSION_NAME} from '@kepler.gl/deckgl-arrow-layers';
import {WKBLoader} from '@loaders.gl/wkt';
import {geojsonToBinary} from '@loaders.gl/gis';
@@ -178,7 +178,7 @@ export function getGeojsonLayerMetaFromArrow({
geoField: ProtoDatasetField;
chunkIndex?: number;
}): GeojsonLayerMetaProps {
- const encoding = geoField?.metadata?.get('ARROW:extension:name');
+ const encoding = geoField?.metadata?.get(GEOARROW_METADATA_KEY);
const options: BinaryGeometriesFromArrowOptions = {
...(chunkIndex !== undefined && chunkIndex >= 0
? {
@@ -191,7 +191,7 @@ export function getGeojsonLayerMetaFromArrow({
};
// getBinaryGeometriesFromArrow doesn't support geoarrow.wkb
- if (encoding === EXTENSION_NAME.WKB) {
+ if (encoding === GEOARROW_EXTENSIONS.WKB) {
return getBinaryGeometriesFromWKBArrow(geoColumn, options);
}
@@ -239,7 +239,7 @@ export function getHoveredObjectFromArrow(
const rawGeometry = col?.get(objectInfo.index);
const field = fieldAccessor(dataContainer);
- const encoding = field?.metadata?.get('ARROW:extension:name');
+ const encoding = field?.metadata?.get(GEOARROW_METADATA_KEY);
const hoveredFeature = parseGeometryFromArrow(rawGeometry, encoding);
@@ -284,7 +284,7 @@ export function getGeoArrowPointFields(fields: Field[]): Field[] {
return fields.filter(field => {
return (
field.type === 'geoarrow' &&
- field.metadata?.get('ARROW:extension:name') === EXTENSION_NAME.POINT
+ field.metadata?.get(GEOARROW_METADATA_KEY) === GEOARROW_EXTENSIONS.POINT
);
});
}
@@ -310,7 +310,7 @@ export function createGeoArrowPointVector(
const precision = 2;
const metadata = new Map();
- metadata.set('ARROW:extension:name', EXTENSION_NAME.POINT);
+ metadata.set(GEOARROW_METADATA_KEY, GEOARROW_EXTENSIONS.POINT);
const childField = new arrow.Field('xyz', new arrow.Float(precision), false, metadata);
const fixedSizeList = new arrow.FixedSizeList(numCoords, childField);
@@ -466,7 +466,7 @@ export function getSatisfiedColumnMode(
export function isGeoArrowPointField(field: Field) {
return (
field.type === 'geoarrow' &&
- field.metadata?.get('ARROW:extension:name') === EXTENSION_NAME.POINT
+ field.metadata?.get(GEOARROW_METADATA_KEY) === GEOARROW_EXTENSIONS.POINT
);
}
diff --git a/src/processors/package.json b/src/processors/package.json
index 814e297ce..80bcfa08c 100644
--- a/src/processors/package.json
+++ b/src/processors/package.json
@@ -45,6 +45,7 @@
"@loaders.gl/loader-utils": "^4.3.2",
"@loaders.gl/parquet": "^4.3.2",
"@loaders.gl/schema": "^4.3.2",
+ "@loaders.gl/wkt": "^4.3.2",
"@mapbox/geojson-normalize": "0.0.1",
"@nebula.gl/edit-modes": "1.0.2-alpha.1",
"@turf/helpers": "^6.1.4",
diff --git a/src/processors/src/data-processor.ts b/src/processors/src/data-processor.ts
index b5de96933..65a6c900e 100644
--- a/src/processors/src/data-processor.ts
+++ b/src/processors/src/data-processor.ts
@@ -5,8 +5,17 @@ import * as arrow from 'apache-arrow';
import {csvParseRows} from 'd3-dsv';
import {DATA_TYPES as AnalyzerDATA_TYPES} from 'type-analyzer';
import normalize from '@mapbox/geojson-normalize';
+import {parseSync} from '@loaders.gl/core';
import {ArrowTable} from '@loaders.gl/schema';
-import {ALL_FIELD_TYPES, DATASET_FORMATS, GUIDES_FILE_FORMAT_DOC} from '@kepler.gl/constants';
+import {WKBLoader} from '@loaders.gl/wkt';
+
+import {
+ ALL_FIELD_TYPES,
+ DATASET_FORMATS,
+ GEOARROW_EXTENSIONS,
+ GEOARROW_METADATA_KEY,
+ GUIDES_FILE_FORMAT_DOC
+} from '@kepler.gl/constants';
import {ProcessorResult, Field} from '@kepler.gl/types';
import {
arrowDataTypeToAnalyzerDataType,
@@ -17,6 +26,7 @@ import {
import {
analyzerTypeToFieldType,
getSampleForTypeAnalyze,
+ getSampleForTypeAnalyzeArrow,
getFieldsFromData,
h3IsValid,
notNullorUndefined,
@@ -393,27 +403,112 @@ export function processArrowTable(arrowTable: ArrowTable): ProcessorResult | nul
return processArrowBatches(arrowTable.data.batches);
}
-export function arrowSchemaToFields(schema: arrow.Schema): Field[] {
- return schema.fields.map((field: arrow.Field, index: number) => {
- const isGeoArrowColumn = field.metadata.get('ARROW:extension:name')?.startsWith('geoarrow');
+/**
+ * Extracts GeoArrow metadata from an Apache Arrow table schema.
+ * For geoparquet files geoarrow metadata isn't present in fields, so extract extra info from schema.
+ * @param table The Apache Arrow table to extract metadata from.
+ * @returns An object mapping column names to their GeoArrow encoding type.
+ * @throws Logs an error message if parsing of metadata fails.
+ */
+export function getGeoArrowMetadataFromSchema(table: arrow.Table): Record<string, string> {
+ const geoArrowMetadata: Record<string, string> = {};
+ try {
+ const geoString = table.schema.metadata?.get('geo');
+ if (geoString) {
+ const parsedGeoString = JSON.parse(geoString);
+ if (parsedGeoString.columns) {
+ Object.keys(parsedGeoString.columns).forEach(columnName => {
+ const columnData = parsedGeoString.columns[columnName];
+ if (columnData?.encoding === 'WKB') {
+ geoArrowMetadata[columnName] = GEOARROW_EXTENSIONS.WKB;
+ }
+ // TODO potentially there are other types but no datasets to test
+ });
+ }
+ }
+ } catch (error) {
+ console.error('An error during arrow table schema metadata parsing');
+ }
+ return geoArrowMetadata;
+}
+
+/**
+ * Converts an Apache Arrow table schema into an array of Kepler.gl field objects.
+ * @param table The Apache Arrow table whose schema needs to be converted.
+ * @param fieldTypeSuggestions Optional mapping of field names to suggested field types.
+ * @returns An array of field objects suitable for Kepler.gl.
+ */
+export function arrowSchemaToFields(
+ table: arrow.Table,
+ fieldTypeSuggestions: Record<string, string> = {}
+): Field[] {
+ const headerRow = table.schema.fields.map(f => f.name);
+ const sample = getSampleForTypeAnalyzeArrow(table, headerRow);
+ const keplerFields = getFieldsFromData(sample, headerRow);
+ const geoArrowMetadata = getGeoArrowMetadataFromSchema(table);
+
+ return table.schema.fields.map((field: arrow.Field, fieldIndex: number) => {
+ let type = arrowDataTypeToFieldType(field.type);
+ let analyzerType = arrowDataTypeToAnalyzerDataType(field.type);
+ let format = '';
+
+ // geometry fields produced by DuckDB's st_asgeojson()
+ if (fieldTypeSuggestions[field.name] === 'JSON') {
+ type = ALL_FIELD_TYPES.geojson;
+ analyzerType = AnalyzerDATA_TYPES.GEOMETRY_FROM_STRING;
+ } else if (
+ fieldTypeSuggestions[field.name] === 'GEOMETRY' ||
+ field.metadata.get(GEOARROW_METADATA_KEY)?.startsWith('geoarrow')
+ ) {
+ type = ALL_FIELD_TYPES.geoarrow;
+ analyzerType = AnalyzerDATA_TYPES.GEOMETRY;
+ } else if (geoArrowMetadata[field.name]) {
+ type = ALL_FIELD_TYPES.geoarrow;
+ analyzerType = AnalyzerDATA_TYPES.GEOMETRY;
+ field.metadata?.set(GEOARROW_METADATA_KEY, geoArrowMetadata[field.name]);
+ } else if (fieldTypeSuggestions[field.name] === 'BLOB') {
+ // When arrow wkb column saved to DuckDB as BLOB without any metadata, then queried back
+ try {
+ const data = table.getChildAt(fieldIndex)?.get(0);
+ if (data) {
+ const binaryGeo = parseSync(data, WKBLoader);
+ if (binaryGeo) {
+ type = ALL_FIELD_TYPES.geoarrow;
+ analyzerType = AnalyzerDATA_TYPES.GEOMETRY;
+ field.metadata?.set(GEOARROW_METADATA_KEY, GEOARROW_EXTENSIONS.WKB);
+ }
+ }
+ } catch (error) {
+ // ignore, not WKB
+ }
+ } else {
+ // TODO should we use Kepler getFieldsFromData instead
+ // of arrowDataTypeToFieldType for all fields?
+ const keplerField = keplerFields[fieldIndex];
+ if (keplerField.type === ALL_FIELD_TYPES.timestamp) {
+ type = keplerField.type;
+ analyzerType = keplerField.analyzerType;
+ format = keplerField.format;
+ }
+ }
+
return {
...field,
name: field.name,
id: field.name,
displayName: field.name,
- format: '',
- fieldIdx: index,
- type: isGeoArrowColumn ? ALL_FIELD_TYPES.geoarrow : arrowDataTypeToFieldType(field.type),
- analyzerType: isGeoArrowColumn
- ? AnalyzerDATA_TYPES.GEOMETRY
- : arrowDataTypeToAnalyzerDataType(field.type),
+ format: format,
+ fieldIdx: fieldIndex,
+ type,
+ analyzerType,
valueAccessor: (dc: any) => d => {
- return dc.valueAt(d.index, index);
+ return dc.valueAt(d.index, fieldIndex);
},
metadata: field.metadata
};
});
}
+
/**
* Parse arrow batches returned from parseInBatches()
*
@@ -425,12 +520,20 @@ export function processArrowBatches(arrowBatches: arrow.RecordBatch[]): Processo
return null;
}
const arrowTable = new arrow.Table(arrowBatches);
- const fields = arrowSchemaToFields(arrowTable.schema);
+ const fields = arrowSchemaToFields(arrowTable);
const cols = [...Array(arrowTable.numCols).keys()].map(i => arrowTable.getChildAt(i));
// return empty rows and use raw arrow table to construct column-wise data container
- return {fields, rows: [], cols, metadata: arrowTable.schema.metadata};
+ return {
+ fields,
+ rows: [],
+ cols,
+ metadata: arrowTable.schema.metadata,
+ // Save original arrow schema, for better ingestion into DuckDB.
+ // TODO consider returning arrowTable in cols, not an array of Vectors from arrowTable.
+ arrowSchema: arrowTable.schema
+ };
}
export const DATASET_HANDLERS = {
diff --git a/src/schemas/src/dataset-schema.ts b/src/schemas/src/dataset-schema.ts
index d273fcde7..f86787e4e 100644
--- a/src/schemas/src/dataset-schema.ts
+++ b/src/schemas/src/dataset-schema.ts
@@ -3,7 +3,7 @@
import pick from 'lodash.pick';
import {console as globalConsole} from 'global/window';
-import {Type as ArrowTypes} from 'apache-arrow';
+import * as arrow from 'apache-arrow';
import {DATASET_FORMATS} from '@kepler.gl/constants';
import {ProtoDataset, RGBColor, JsonObject} from '@kepler.gl/types';
@@ -117,11 +117,10 @@ const getAllDataForSaving = (dataContainer: DataContainerInterface): any[][] =>
for (let columnIndex = 0; columnIndex < numColumns; ++columnIndex) {
const column = dataContainer.getColumn(columnIndex);
- const typeId = column.type?.typeId;
if (
- typeId === ArrowTypes.Timestamp ||
- typeId === ArrowTypes.Date ||
- typeId === ArrowTypes.Time
+ arrow.DataType.isTimestamp(column.type) ||
+ arrow.DataType.isDate(column.type) ||
+ arrow.DataType.isTime(column.type)
) {
allData.forEach(row => {
row[columnIndex] = new Date(row[columnIndex]).toISOString();
diff --git a/src/types/types.d.ts b/src/types/types.d.ts
index c2d3af446..e9c306b03 100644
--- a/src/types/types.d.ts
+++ b/src/types/types.d.ts
@@ -32,6 +32,9 @@ export type ProcessorResult = {
rows: any[][];
cols?: any[];
metadata?: any;
+ /** Optional schema for arrow tables with metadata preserved. */
+ // TODO: Should we use a loaded arrow.Table in cols instead of an array of arrow.Vectors? Why was an array of arrow.Vectors chosen?
+ arrowSchema?: any;
} | null;
export type Json = JsonScalar | JsonArray | JsonObject;
@@ -41,3 +44,17 @@ export type JsonArray = Json[];
export type JsonObject = {
[key: string]: Json | undefined;
};
+
+/**
+ * Types to mock apache-arrow types
+ */
+
+export interface ApacheVectorInterface {
+ length: number;
+}
+
+export interface ArrowTableInterface {
+ get numRows(): number;
+
+ getChildAt: (index: number) => Vector;
+}
diff --git a/src/utils/src/dataset-utils.ts b/src/utils/src/dataset-utils.ts
index 1d4032780..930941ba1 100644
--- a/src/utils/src/dataset-utils.ts
+++ b/src/utils/src/dataset-utils.ts
@@ -1,13 +1,18 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
+import * as arrow from 'apache-arrow';
import {
ALL_FIELD_TYPES,
FIELD_OPTS,
TOOLTIP_FORMATS,
TOOLTIP_FORMAT_TYPES
} from '@kepler.gl/constants';
-import {getSampleForTypeAnalyze, getFieldsFromData} from '@kepler.gl/common-utils';
+import {
+ getSampleForTypeAnalyze,
+ getSampleForTypeAnalyzeArrow,
+ getFieldsFromData
+} from '@kepler.gl/common-utils';
import {Analyzer} from 'type-analyzer';
import assert from 'assert';
@@ -260,21 +265,25 @@ export function validateInputData(data: ProtoDataset['data']): ProcessorResult {
return false;
}
- if (!fields.every(field => field.analyzerType)) {
- assert('field missing analyzerType');
+ if (!f.analyzerType) {
+ assert(`field ${i} missing analyzerType`);
return false;
}
// check time format is correct based on first 10 not empty element
if (f.type === ALL_FIELD_TYPES.timestamp) {
- const sample = findNonEmptyRowsAtField(rows, i, 10).map(r => ({ts: r[i]}));
+ const sample = (
+ cols ? findNonEmptyRowsAtFieldArrow(cols, i, 10) : findNonEmptyRowsAtField(rows, i, 10)
+ ).map(r => ({ts: r[i]}));
const analyzedType = Analyzer.computeColMeta(sample)[0];
return analyzedType && analyzedType.category === 'TIME' && analyzedType.format === f.format;
}
// check existing string field is H3 type
if (f.type === ALL_FIELD_TYPES.string) {
- const sample = findNonEmptyRowsAtField(rows, i, 10).map(r => r[i]);
+ const sample = (
+ cols ? findNonEmptyRowsAtFieldArrow(cols, i, 10) : findNonEmptyRowsAtField(rows, i, 10)
+ ).map(r => r[i]);
return sample.every(item => !h3IsValid(item));
}
@@ -287,10 +296,15 @@ export function validateInputData(data: ProtoDataset['data']): ProcessorResult {
// if any field has missing type, recalculate it for everyone
// because we simply lost faith in humanity
- const sampleData = getSampleForTypeAnalyze({
- fields: fields.map(f => f.name),
- rows
- });
+ const sampleData = cols
+ ? getSampleForTypeAnalyzeArrow(
+ cols,
+ fields.map(f => f.name)
+ )
+ : getSampleForTypeAnalyze({
+ fields: fields.map(f => f.name),
+ rows
+ });
const fieldOrder = fields.map(f => f.name);
const meta = getFieldsFromData(sampleData, fieldOrder);
const updatedFields = fields.map((f, i) => ({
@@ -315,6 +329,24 @@ function findNonEmptyRowsAtField(rows: unknown[][], fieldIdx: number, total: num
return sample;
}
+function findNonEmptyRowsAtFieldArrow(
+ cols: arrow.Vector[],
+ fieldIdx: number,
+ total: number
+): any[] {
+ const sample: any[] = [];
+ const numRows = cols[fieldIdx].length;
+ let i = 0;
+ while (sample.length < total && i < numRows) {
+ if (notNullorUndefined(cols[fieldIdx].get(i))) {
+ const row = cols.map(col => col.get(i));
+ sample.push(row);
+ }
+ i++;
+ }
+ return sample;
+}
+
const TIME_DISPLAY = '2020-05-11 14:00';
export const addTimeLabel = (formats: TimeLabelFormat[]) =>
diff --git a/yarn.lock b/yarn.lock
index 2f34fd079..a45e9e244 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -3300,7 +3300,7 @@ __metadata:
languageName: unknown
linkType: soft
-"@kepler.gl/constants@npm:3.1.0, @kepler.gl/constants@workspace:src/constants":
+"@kepler.gl/constants@npm:3.1.0, @kepler.gl/constants@npm:^3.1.0, @kepler.gl/constants@workspace:src/constants":
version: 0.0.0-use.local
resolution: "@kepler.gl/constants@workspace:src/constants"
dependencies:
@@ -3327,6 +3327,7 @@ __metadata:
resolution: "@kepler.gl/deckgl-arrow-layers@workspace:src/deckgl-arrow-layers"
dependencies:
"@geoarrow/geoarrow-js": "npm:^0.3.0"
+ "@kepler.gl/constants": "npm:^3.1.0"
"@math.gl/core": "npm:^4.0.0"
"@math.gl/polygon": "npm:^4.0.0"
"@math.gl/types": "npm:^4.0.0"
@@ -3495,6 +3496,7 @@ __metadata:
"@loaders.gl/loader-utils": "npm:^4.3.2"
"@loaders.gl/parquet": "npm:^4.3.2"
"@loaders.gl/schema": "npm:^4.3.2"
+ "@loaders.gl/wkt": "npm:^4.3.2"
"@mapbox/geojson-normalize": "npm:0.0.1"
"@nebula.gl/edit-modes": "npm:1.0.2-alpha.1"
"@turf/helpers": "npm:^6.1.4"