geonetwork-ui 2.11.0-dev.e7b8ec331 → 2.11.0-dev.f5ee66b24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/fesm2022/geonetwork-ui.mjs +1482 -928
  2. package/fesm2022/geonetwork-ui.mjs.map +1 -1
  3. package/index.d.ts +280 -124
  4. package/index.d.ts.map +1 -1
  5. package/package.json +12 -11
  6. package/src/libs/api/metadata-converter/src/lib/gn4/gn4.field.mapper.ts +43 -13
  7. package/src/libs/api/repository/src/lib/gn4/elasticsearch/elasticsearch.service.ts +108 -34
  8. package/src/libs/api/repository/src/lib/gn4/gn4-repository.ts +40 -16
  9. package/src/libs/common/domain/src/lib/model/record/metadata.model.ts +12 -0
  10. package/src/libs/common/domain/src/lib/model/search/filter.model.ts +20 -1
  11. package/src/libs/common/domain/src/lib/repository/records-repository.interface.ts +2 -2
  12. package/src/libs/feature/dataviz/src/lib/chart-view/chart-view.component.ts +3 -2
  13. package/src/libs/feature/dataviz/src/lib/geo-table-view/geo-table-view.component.ts +2 -1
  14. package/src/libs/feature/dataviz/src/lib/service/data.service.ts +22 -22
  15. package/src/libs/feature/map/src/index.ts +0 -1
  16. package/src/libs/feature/map/src/lib/add-layer-from-file/add-layer-from-file.component.html +1 -0
  17. package/src/libs/feature/map/src/lib/feature-map.module.ts +1 -8
  18. package/src/libs/feature/notifications/src/lib/notifications.service.ts +6 -4
  19. package/src/libs/feature/record/src/lib/state/mdview.actions.ts +4 -8
  20. package/src/libs/feature/record/src/lib/state/mdview.effects.ts +7 -16
  21. package/src/libs/feature/record/src/lib/state/mdview.facade.ts +1 -3
  22. package/src/libs/feature/record/src/lib/state/mdview.reducer.ts +4 -9
  23. package/src/libs/feature/record/src/lib/state/mdview.selectors.ts +2 -7
  24. package/src/libs/feature/router/src/lib/default/state/query-params.utils.ts +1 -1
  25. package/src/libs/feature/search/src/index.ts +2 -0
  26. package/src/libs/feature/search/src/lib/filter-dropdown/filter-dropdown.component.html +12 -4
  27. package/src/libs/feature/search/src/lib/filter-dropdown/filter-dropdown.component.ts +58 -19
  28. package/src/libs/feature/{map/src/lib → search/src/lib/geocoding}/geocoding.service.ts +5 -1
  29. package/src/libs/feature/search/src/lib/location-search/location-search.component.html +8 -0
  30. package/src/libs/feature/search/src/lib/location-search/location-search.component.ts +40 -0
  31. package/src/libs/feature/search/src/lib/search-filters-summary-item/search-filters-summary-item.component.ts +18 -8
  32. package/src/libs/feature/search/src/lib/utils/service/fields.service.ts +9 -1
  33. package/src/libs/feature/search/src/lib/utils/service/fields.ts +61 -2
  34. package/src/libs/ui/dataviz/src/lib/data-table/data-table.component.html +6 -7
  35. package/src/libs/ui/dataviz/src/lib/data-table/data-table.component.ts +31 -19
  36. package/src/libs/ui/dataviz/src/lib/data-table/data-table.fixtures.ts +2 -2
  37. package/src/libs/ui/elements/src/lib/service-capabilities/service-capabilities.component.ts +2 -1
  38. package/src/libs/ui/inputs/src/index.ts +2 -0
  39. package/src/libs/ui/inputs/src/lib/autocomplete/autocomplete.component.html +10 -1
  40. package/src/libs/ui/inputs/src/lib/autocomplete/autocomplete.component.ts +8 -0
  41. package/src/libs/ui/inputs/src/lib/date-adapter.providers.ts +30 -0
  42. package/src/libs/ui/inputs/src/lib/date-picker/date-picker.component.ts +3 -24
  43. package/src/libs/ui/inputs/src/lib/date-range-dropdown/date-range-dropdown.component.css +37 -3
  44. package/src/libs/ui/inputs/src/lib/date-range-dropdown/date-range-dropdown.component.html +135 -16
  45. package/src/libs/ui/inputs/src/lib/date-range-dropdown/date-range-dropdown.component.ts +166 -29
  46. package/src/libs/ui/inputs/src/lib/date-range-picker/date-range-picker.component.ts +3 -7
  47. package/src/libs/ui/inputs/src/lib/drag-and-drop-file-input/drag-and-drop-file-input.component.css +1 -0
  48. package/src/libs/ui/inputs/src/lib/drag-and-drop-file-input/drag-and-drop-file-input.component.html +20 -7
  49. package/src/libs/ui/inputs/src/lib/drag-and-drop-file-input/drag-and-drop-file-input.component.ts +46 -5
  50. package/src/libs/ui/inputs/src/lib/dropdown-multiselect/dropdown-multiselect.component.html +7 -4
  51. package/src/libs/ui/inputs/src/lib/dropdown-multiselect/dropdown-multiselect.component.ts +12 -9
  52. package/src/libs/ui/inputs/src/lib/dropdown-multiselect/dropdown-multiselect.model.ts +2 -2
  53. package/src/libs/ui/inputs/src/lib/spatial-extent-dropdown/spatial-extent-dropdown.component.html +111 -0
  54. package/src/libs/ui/inputs/src/lib/spatial-extent-dropdown/spatial-extent-dropdown.component.ts +215 -0
  55. package/src/libs/ui/map/src/lib/components/map-container/map-container.component.ts +6 -5
  56. package/src/libs/util/app-config/src/lib/app-config.ts +3 -0
  57. package/src/libs/util/app-config/src/lib/model.ts +1 -0
  58. package/src/libs/util/data-fetcher/src/lib/data-fetcher.ts +19 -22
  59. package/src/libs/util/data-fetcher/src/lib/engine/duckdb.ts +185 -0
  60. package/src/libs/util/data-fetcher/src/lib/engine/results.ts +63 -0
  61. package/src/libs/util/data-fetcher/src/lib/{sql-utils.ts → engine/sql-utils.ts} +28 -13
  62. package/src/libs/util/data-fetcher/src/lib/model.ts +2 -1
  63. package/src/libs/util/data-fetcher/src/lib/readers/base-file.ts +53 -38
  64. package/src/libs/util/data-fetcher/src/lib/readers/base.ts +11 -0
  65. package/src/libs/util/data-fetcher/src/lib/readers/csv.ts +9 -47
  66. package/src/libs/util/data-fetcher/src/lib/readers/excel.ts +27 -27
  67. package/src/libs/util/data-fetcher/src/lib/readers/geojson.ts +5 -24
  68. package/src/libs/util/data-fetcher/src/lib/readers/gml.ts +5 -49
  69. package/src/libs/util/data-fetcher/src/lib/readers/json.ts +5 -23
  70. package/src/libs/util/data-fetcher/src/lib/readers/wfs.ts +184 -128
  71. package/src/libs/util/data-fetcher/src/lib/utils.ts +0 -143
  72. package/src/libs/util/shared/src/index.ts +1 -0
  73. package/src/libs/util/shared/src/lib/autofocus.directive.ts +26 -0
  74. package/src/libs/util/shared/src/lib/links/link-utils.ts +19 -10
  75. package/src/libs/util/shared/src/lib/services/date.service.ts +3 -3
  76. package/src/libs/util/shared/src/lib/utils/file.ts +15 -0
  77. package/src/libs/util/shared/src/lib/utils/geojson.ts +8 -0
  78. package/src/libs/util/shared/src/lib/utils/index.ts +1 -0
  79. package/tailwind.base.css +5 -0
  80. package/translations/de.json +17 -3
  81. package/translations/en.json +16 -2
  82. package/translations/es.json +15 -1
  83. package/translations/fr.json +17 -3
  84. package/translations/it.json +15 -1
  85. package/translations/nl.json +15 -1
  86. package/translations/pt.json +15 -1
  87. package/translations/sk.json +15 -1
  88. package/src/libs/feature/map/src/lib/geocoding/geocoding.component.html +0 -41
  89. package/src/libs/feature/map/src/lib/geocoding/geocoding.component.ts +0 -112
  90. package/src/libs/util/data-fetcher/src/lib/readers/base-cache.ts +0 -14
  91. /package/src/libs/{feature/map/src/lib/geocoding/geocoding.component.css → ui/inputs/src/lib/spatial-extent-dropdown/spatial-extent-dropdown.component.css} +0 -0
@@ -0,0 +1,185 @@
1
+ import * as duckdb from '@duckdb/duckdb-wasm'
2
+ import { DataItem, FetchError, PropertyInfo } from '../model'
3
+ import { arrowTableToDataItems } from './results'
4
+ import { Table } from 'apache-arrow'
5
+
6
+ // init code taken from https://github.com/duckdb/duckdb-wasm/blob/main/packages/duckdb-wasm/README.md
7
+ const JSDELIVR_BUNDLES = duckdb.getJsDelivrBundles()
8
+
9
+ // from https://duckdb.org/docs/current/sql/data_types/overview
10
+ const typesMapping: Record<string, PropertyInfo['type']> = {
11
+ INTEGER: 'number',
12
+ SMALLINT: 'number',
13
+ TINYINT: 'number',
14
+ BIGINT: 'number',
15
+ HUGEINT: 'number',
16
+ UINTEGER: 'number',
17
+ USMALLINT: 'number',
18
+ UTINYINT: 'number',
19
+ UBIGINT: 'number',
20
+ UHUGEINT: 'number',
21
+ DOUBLE: 'number',
22
+ BIGNUM: 'number',
23
+ DECIMAL: 'number',
24
+ NUMERIC: 'number',
25
+ FLOAT: 'number',
26
+ REAL: 'number',
27
+ 'TIMESTAMP WITH TIME ZONE': 'date',
28
+ TIMESTAMP: 'date',
29
+ DATE: 'date',
30
+ CHAR: 'string',
31
+ VARCHAR: 'string',
32
+ TEXT: 'string',
33
+ UUID: 'string',
34
+ BLOB: 'string',
35
+ BIT: 'string',
36
+ INTERVAL: 'string',
37
+ LIST: 'string',
38
+ BOOLEAN: 'boolean',
39
+ }
40
+
41
+ export class Engine {
42
+ private db: duckdb.AsyncDuckDB
43
+ private init_: Promise<Engine>
44
+
45
+ private async makeInit(): Promise<Engine> {
46
+ const bundle = await duckdb.selectBundle(JSDELIVR_BUNDLES)
47
+ let worker_url = bundle.mainWorker
48
+
49
+ // this is necessary to let browsers execute WASM code coming from a cross-origin host
50
+ if (worker_url.startsWith('https://')) {
51
+ worker_url = URL.createObjectURL(
52
+ new Blob([`importScripts("${worker_url}");`], {
53
+ type: 'text/javascript',
54
+ })
55
+ )
56
+ }
57
+ const worker = new Worker(worker_url)
58
+ const logger = new duckdb.ConsoleLogger(duckdb.LogLevel.WARNING)
59
+ this.db = new duckdb.AsyncDuckDB(logger, worker)
60
+ await this.db.instantiate(bundle.mainModule, bundle.pthreadWorker)
61
+
62
+ // setup duckdb options
63
+ const conn = await this.db.connect()
64
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
65
+ await conn.query(`INSTALL spatial; LOAD spatial;`)
66
+ await conn.query(`SET TimeZone = '${timezone}';`)
67
+ await conn.query(`SET threads = 1;`)
68
+ // await conn.query(`SET memory_limit = '2GB';`) // used for experimenting when we encounter memory issues
69
+ await conn.query(`SET preserve_insertion_order = false;`) // this reduces memory usage when loading a dataset
70
+ conn.close()
71
+ return this
72
+ }
73
+
74
+ isReady(): Promise<Engine> {
75
+ if (!this.init_) {
76
+ this.init_ = this.makeInit()
77
+ }
78
+ return this.init_
79
+ }
80
+
81
+ /**
82
+ * Returns information about a dataset once it's loaded:
83
+ * - a list of properties description
84
+ * - the name of the dataset geometry column (null if no geometry present)
85
+ * @param datasetId name of the table under which the dataset will be stored
86
+ * @param loadQuery duckdb-specific query for creating a table out of the data
87
+ * @param forceReload if true, any existing data will be dropped and redownloaded
88
+ */
89
+ async loadFile(
90
+ datasetId: string,
91
+ loadQuery: string,
92
+ forceReload = false
93
+ ): Promise<{
94
+ properties: PropertyInfo[]
95
+ geometryColumn: string | null
96
+ rowsCount: number
97
+ }> {
98
+ const conn = await this.db.connect()
99
+ let results: Table
100
+
101
+ // either we want to recreate the table, or we keep it if it already exists
102
+ const safeLoadQuery = forceReload
103
+ ? `DROP TABLE IF EXISTS ${datasetId};
104
+ ${loadQuery}`
105
+ : loadQuery.replace(
106
+ /CREATE TABLE(?! IF NOT EXISTS)/gi,
107
+ 'CREATE TABLE IF NOT EXISTS'
108
+ )
109
+
110
+ // create the table
111
+ try {
112
+ results = await conn.query(safeLoadQuery)
113
+ } catch (e: unknown) {
114
+ throw new FetchError(
115
+ 'parse',
116
+ `DuckDB encountered an error when loading the data: ${(e as Error).message}`
117
+ )
118
+ }
119
+
120
+ // read rows count
121
+ results = await conn.query(`SELECT count(*) FROM ${datasetId}`)
122
+ const { 'count_star()': recordsCount } = results.toArray()[0].toJSON()
123
+
124
+ // read columns
125
+ results = await conn.query(
126
+ `SELECT * FROM information_schema.columns WHERE table_name = '${datasetId}';`
127
+ )
128
+ let geometryColumn: string | null = null
129
+
130
+ const properties = results
131
+ .toArray()
132
+ .map((row) => {
133
+ const rowObj = row.toJSON()
134
+ if (rowObj['data_type'] === 'GEOMETRY') {
135
+ // the geometry is not part of the properties
136
+ // note: right now we only keep one geometry column name, but if there are multiple they will
137
+ // all get discarded
138
+ geometryColumn = rowObj['column_name']
139
+ return null
140
+ }
141
+ return {
142
+ name: rowObj['column_name'],
143
+ label: rowObj['column_name'],
144
+ type: typesMapping[rowObj['data_type']] ?? 'other',
145
+ } as PropertyInfo
146
+ })
147
+ .filter((prop) => prop !== null)
148
+
149
+ conn.close()
150
+
151
+ return {
152
+ properties,
153
+ geometryColumn,
154
+ rowsCount: Number(recordsCount),
155
+ }
156
+ }
157
+
158
+ // register a Uint8 buffer using a handle in the duckdb instance
159
+ async registerData(name: string, buffer: Uint8Array) {
160
+ return this.db.registerFileBuffer(name, buffer)
161
+ }
162
+
163
+ /**
164
+ * @param query duckdb-specific query for fetching items
165
+ */
166
+ async queryItems(query: string): Promise<DataItem[]> {
167
+ const conn = await this.db.connect()
168
+ const results = await conn.query(query)
169
+ conn.close()
170
+ return arrowTableToDataItems(results)
171
+ }
172
+
173
+ close() {
174
+ this.db?.terminate()
175
+ }
176
+ }
177
+
178
+ let engine: Engine | null = null
179
+
180
+ export async function getEngine(): Promise<Engine> {
181
+ if (!engine) {
182
+ engine = new Engine()
183
+ }
184
+ return engine.isReady()
185
+ }
@@ -0,0 +1,63 @@
1
+ import { DataItem } from '../model'
2
+ import { Feature } from 'geojson'
3
+ import { DataType, StructRow, Table, Vector } from 'apache-arrow'
4
+ import { GEOMETRY_COLUMN_ALIAS } from './sql-utils'
5
+
6
+ export function arrowTableToDataItems(
7
+ table: Table<{ [key: string]: DataType }>
8
+ ): DataItem[] {
9
+ const fields = table.schema.fields
10
+
11
+ return table.toArray().map((row: StructRow) => {
12
+ const rowJson = row.toJSON()
13
+ const feature: Feature = {
14
+ type: 'Feature',
15
+ geometry: null,
16
+ properties: {},
17
+ }
18
+ const keys = Object.keys(rowJson)
19
+ for (let i = 0; i < keys.length; i++) {
20
+ const key = keys[i]
21
+ const dataType = fields[i].type
22
+ let value = rowJson[key]
23
+ // this might happen if we get an array inside a field
24
+ if (value instanceof Vector) {
25
+ value = Array.from(value)
26
+ }
27
+ // cast bigints to ints
28
+ if (typeof value === 'bigint') {
29
+ value = Number(value)
30
+ }
31
+ // rename columns with empty name
32
+ if (!key) {
33
+ feature.properties['unknown'] = value
34
+ continue
35
+ }
36
+ // assign properties that look like an id to the geojson `id` field
37
+ if (
38
+ /^(object|feature)?_?id$/.test(key.toLowerCase()) &&
39
+ (typeof value == 'string' || typeof value === 'number')
40
+ ) {
41
+ feature.id = value
42
+ }
43
+ // if a date is in timestamp (number) format, convert it to native
44
+ if (
45
+ typeof value === 'number' &&
46
+ (DataType.isTimestamp(dataType) || DataType.isDate(dataType))
47
+ ) {
48
+ value = new Date(value)
49
+ }
50
+ // if a binary field (most likely a geometry column): skip
51
+ if (DataType.isBinary(dataType)) {
52
+ continue
53
+ }
54
+ // geometry column
55
+ if (key === GEOMETRY_COLUMN_ALIAS && DataType.isUtf8(dataType)) {
56
+ feature.geometry = JSON.parse(value)
57
+ continue
58
+ }
59
+ feature.properties[key] = value
60
+ }
61
+ return feature
62
+ })
63
+ }
@@ -4,7 +4,13 @@ import {
4
4
  FieldGroupBy,
5
5
  FieldName,
6
6
  FieldSort,
7
- } from './model'
7
+ } from '../model'
8
+
9
+ export const GEOMETRY_COLUMN_ALIAS = '__geometry__'
10
+
11
+ function fieldToSql(name: string): string {
12
+ return `"${name.replace(/"/g, '""')}"` // escape double quotes in field names
13
+ }
8
14
 
9
15
  function filterToSql(filter: FieldFilter): string {
10
16
  const operator = filter[0]
@@ -20,12 +26,12 @@ function filterToSql(filter: FieldFilter): string {
20
26
  case '=':
21
27
  case '!=':
22
28
  case 'like':
23
- return `[${args[0]}] ${operator.toUpperCase()} ${valueToSql(
29
+ return `${fieldToSql(args[0] as string)} ${operator.toUpperCase()} ${valueToSql(
24
30
  args[1] as string | number
25
31
  )}`
26
32
  case 'in': {
27
33
  const values = args.slice(1) as string[] | number[]
28
- return `[${args[0]}] IN (${values.map(valueToSql).join(', ')})`
34
+ return `${fieldToSql(args[0] as string)} IN (${values.map(valueToSql).join(', ')})`
29
35
  }
30
36
  case 'and':
31
37
  case 'or': {
@@ -48,18 +54,19 @@ function aggregationToSql(aggregation: FieldAggregation): string {
48
54
 
49
55
  switch (operation) {
50
56
  case 'average':
51
- return `AVG([${field}]) as [average(${field})]`
57
+ return `CAST(AVG(${fieldToSql(field)}) AS DOUBLE) as ${fieldToSql(`average(${field})`)}`
52
58
  case 'sum':
53
59
  case 'max':
54
60
  case 'min':
55
- return `${operation.toUpperCase()}([${field}]) as [${operation}(${field})]`
61
+ return `CAST(${operation.toUpperCase()}(${fieldToSql(field)}) AS DOUBLE) as ${fieldToSql(`${operation}(${field})`)}`
56
62
  case 'count':
57
- return 'COUNT(*) as [count()]'
63
+ return 'CAST(COUNT(*) AS INTEGER) as "count()"' // we don't need Bigint precision here
58
64
  }
59
65
  }
60
66
 
61
67
  /**
62
68
  * Leave arguments at null if not used
69
+ * @param tableName
63
70
  * @param selected
64
71
  * @param filter
65
72
  * @param sort
@@ -69,29 +76,34 @@ function aggregationToSql(aggregation: FieldAggregation): string {
69
76
  * @param aggregations
70
77
  */
71
78
  export function generateSqlQuery(
79
+ tableName: string,
72
80
  selected: FieldName[] = null,
73
81
  filter: FieldFilter = null,
74
82
  sort: FieldSort[] = null,
75
83
  startIndex: number = null,
76
84
  count: number = null,
77
85
  groupBy: FieldGroupBy[] = null,
78
- aggregations: FieldAggregation[] = null
86
+ aggregations: FieldAggregation[] = null,
87
+ geometryColumn: string = null
79
88
  ): string {
80
89
  let sqlSelect = 'SELECT *'
81
- const sqlFrom = ' FROM ?'
90
+ const sqlFrom = ` FROM ${tableName}`
82
91
  let sqlOrderBy = ''
83
92
  let sqlWhere = ''
84
93
  let sqlLimit = ''
85
94
  let sqlGroupBy = ''
86
95
  if (selected !== null) {
87
- sqlSelect = `SELECT ${selected.map((name) => `[${name}]`).join(', ')}`
96
+ sqlSelect = `SELECT ${selected.map(fieldToSql).join(', ')}`
97
+ }
98
+ if (geometryColumn !== null) {
99
+ sqlSelect += `, ST_AsGeoJSON(${fieldToSql(geometryColumn)}) as ${GEOMETRY_COLUMN_ALIAS}`
88
100
  }
89
101
  if (filter !== null) {
90
102
  sqlWhere = ` WHERE ${filterToSql(filter)}`
91
103
  }
92
104
  if (sort?.length) {
93
105
  sqlOrderBy = ` ORDER BY ${sort
94
- .map((sort) => `[${sort[1]}] ${sort[0].toUpperCase()}`)
106
+ .map((sort) => `${fieldToSql(sort[1])} ${sort[0].toUpperCase()}`)
95
107
  .join(', ')}`
96
108
  }
97
109
  if (startIndex !== null && count !== null) {
@@ -101,15 +113,18 @@ export function generateSqlQuery(
101
113
  sqlSelect = `SELECT ${aggregations.map(aggregationToSql).join(', ')}`
102
114
  const groupedByDistinct = groupBy.filter((group) => group[0] === 'distinct')
103
115
  const sqlGroupByFields = groupedByDistinct
104
- .map((group) => `[${group[1]}]`)
116
+ .map((group) => fieldToSql(group[1]))
105
117
  .join(', ')
106
118
  const sqlGroupBySelect = groupedByDistinct
107
- .map((group) => `[${group[1]}] as [distinct(${group[1]})]`)
119
+ .map(
120
+ (group) =>
121
+ `${fieldToSql(group[1])} as ${fieldToSql(`distinct(${group[1]})`)}`
122
+ )
108
123
  .join(', ')
109
124
  if (sqlGroupByFields && sqlGroupBySelect) {
110
125
  sqlGroupBy = ` GROUP BY ${sqlGroupByFields}`
111
126
  sqlSelect += `, ${sqlGroupBySelect}`
112
127
  }
113
128
  }
114
- return sqlSelect + sqlFrom + sqlGroupBy + sqlOrderBy + sqlWhere + sqlLimit
129
+ return sqlSelect + sqlFrom + sqlGroupBy + sqlWhere + sqlOrderBy + sqlLimit
115
130
  }
@@ -97,11 +97,12 @@ export interface DatasetHeaders {
97
97
  export interface PropertyInfo {
98
98
  name: string
99
99
  label: string
100
- type: 'number' | 'date' | 'url' | 'string'
100
+ type: 'number' | 'date' | 'boolean' | 'string' | 'other'
101
101
  }
102
102
 
103
103
  export interface DatasetInfo {
104
104
  itemsCount: number
105
+ hasGeometry: boolean
105
106
  }
106
107
 
107
108
  export type FieldName = string
@@ -1,65 +1,80 @@
1
1
  import { DataItem, DatasetInfo, PropertyInfo } from '../model'
2
- import { getJsonDataItemsProxy, jsonToGeojsonFeature } from '../utils'
3
- import { generateSqlQuery } from '../sql-utils'
4
- import { BaseCacheReader } from './base-cache'
2
+ import { generateSqlQuery } from '../engine/sql-utils'
3
+ import { Engine, getEngine } from '../engine/duckdb'
4
+ import { BaseReader } from './base'
5
5
 
6
- type ParseResult = {
7
- items: DataItem[]
8
- properties: PropertyInfo[]
9
- }
6
+ /**
7
+ * This reader handles file formats supported natively by DuckDB
8
+ */
9
+ export class BaseFileReader extends BaseReader {
10
+ protected engine: Engine
11
+ protected datasetId: string
12
+ protected properties_: PropertyInfo[]
13
+ protected geometryColumn: string
14
+ protected rowsCount: number
10
15
 
11
- export class BaseFileReader extends BaseCacheReader {
12
- private parseResult_: Promise<ParseResult>
16
+ // a table id should not exceed 63 chars
17
+ protected generateDatasetId() {
18
+ // generate a hash out of the url
19
+ let hash = 0
20
+ for (const char of this.url) {
21
+ hash = (hash << 5) - hash + char.charCodeAt(0)
22
+ hash = hash >>> 0 // make it unsigned
23
+ }
24
+ return `datafetcher_${hash.toString(16)}`
25
+ }
13
26
 
14
- protected getData(): Promise<ParseResult> {
27
+ protected async getLoadQuery(): Promise<string> {
15
28
  throw new Error('not implemented')
16
29
  }
17
30
 
18
- load() {
19
- this.parseResult_ = this.getData()
31
+ async load() {
32
+ this.datasetId = this.generateDatasetId()
33
+ this.loadPromise_ = getEngine()
34
+ .then((engine) => {
35
+ this.engine = engine
36
+ return this.getLoadQuery()
37
+ })
38
+ .then((loadQuery) =>
39
+ this.engine.loadFile(this.datasetId, loadQuery, !this.cacheEnabled)
40
+ )
41
+ .then((datasetInfo) => {
42
+ this.properties_ = datasetInfo.properties
43
+ this.geometryColumn = datasetInfo.geometryColumn
44
+ this.rowsCount = datasetInfo.rowsCount
45
+ // returns void for the loaded promise
46
+ })
20
47
  }
21
48
 
22
49
  get properties(): Promise<PropertyInfo[]> {
23
- return this.parseResult_.then((result) => result.properties)
50
+ return this.isLoaded.then(() => this.properties_)
24
51
  }
25
52
 
26
53
  get info(): Promise<DatasetInfo> {
27
- return this.parseResult_.then(
28
- (result) =>
29
- ({
30
- itemsCount: result.items.length,
31
- }) as DatasetInfo
32
- )
54
+ return this.isLoaded.then(() => ({
55
+ itemsCount: this.rowsCount,
56
+ hasGeometry: !!this.geometryColumn,
57
+ }))
33
58
  }
34
59
 
35
60
  async read(): Promise<DataItem[]> {
36
- const items = (await this.parseResult_).items
37
- // no query defined: return the full results as is
38
- if (
39
- this.groupedBy == null &&
40
- this.aggregations == null &&
41
- this.selected == null &&
42
- this.sort == null &&
43
- this.filter == null &&
44
- this.startIndex == null &&
45
- this.count == null
46
- ) {
47
- return items
48
- }
61
+ await this.isLoaded
62
+
63
+ // if only certain fields are selected, omit the geometry
64
+ const geometryColumn = this.selected === null ? this.geometryColumn : null
49
65
 
50
- const jsonItems = getJsonDataItemsProxy(items)
51
66
  const query = generateSqlQuery(
67
+ this.datasetId,
52
68
  this.selected,
53
69
  this.filter,
54
70
  this.sort,
55
71
  this.startIndex,
56
72
  this.count,
57
73
  this.groupedBy,
58
- this.aggregations
74
+ this.aggregations,
75
+ geometryColumn
59
76
  )
60
- const result: any[] = await import('alasql').then((module) =>
61
- module.default(query, [jsonItems])
62
- )
63
- return result.map(jsonToGeojsonFeature)
77
+
78
+ return this.engine.queryItems(query)
64
79
  }
65
80
  }
@@ -17,13 +17,24 @@ export class BaseReader {
17
17
  protected sort: FieldSort[] = null
18
18
  protected startIndex: number = null
19
19
  protected count: number = null
20
+ protected loadPromise_: Promise<void> = Promise.resolve()
21
+
22
+ protected cacheEnabled = false
20
23
 
21
24
  constructor(protected url: string) {}
22
25
 
26
+ enableCache(enabled: boolean) {
27
+ this.cacheEnabled = enabled
28
+ }
29
+
23
30
  load() {
24
31
  throw new Error('not implemented')
25
32
  }
26
33
 
34
+ get isLoaded() {
35
+ return this.loadPromise_
36
+ }
37
+
27
38
  get properties(): Promise<PropertyInfo[]> {
28
39
  throw new Error('not implemented')
29
40
  }
@@ -1,52 +1,14 @@
1
- import * as Papa from 'papaparse'
2
- import { DataItem, PropertyInfo } from '../model'
3
- import {
4
- fetchDataAsText,
5
- jsonToGeojsonFeature,
6
- processItemProperties,
7
- } from '../utils'
8
1
  import { BaseFileReader } from './base-file'
9
2
 
10
- export function parseCsv(text: string): {
11
- items: DataItem[]
12
- properties: PropertyInfo[]
13
- } {
14
- // first parse the header to guess the delimiter
15
- // note that we do that to not rely on Papaparse logic for guessing delimiter
16
- let delimiter
17
- try {
18
- const header = text.split('\n')[0]
19
- const result = Papa.parse(header, {
20
- header: false,
21
- })
22
- delimiter = result.meta.delimiter
23
- } catch (e) {
24
- throw new Error('CSV parsing failed: the delimiter could not be guessed')
25
- }
26
-
27
- const parsed = Papa.parse(text, {
28
- header: true,
29
- skipEmptyLines: true,
30
- delimiter,
31
- })
32
- if (parsed.errors.length) {
33
- throw new Error(
34
- 'CSV parsing failed for the following reasons:\n' +
35
- parsed.errors
36
- .map(
37
- (error) =>
38
- `* ${error.message} at row ${error.row}, column ${error.index}`
39
- )
40
- .join('\n')
41
- )
42
- }
43
-
44
- const items = (parsed.data as any[]).map(jsonToGeojsonFeature)
45
- return processItemProperties(items, true)
46
- }
47
-
48
3
  export class CsvReader extends BaseFileReader {
49
- getData() {
50
- return fetchDataAsText(this.url, this.cacheActive).then(parseCsv)
4
+ async getLoadQuery() {
5
+ // first we get a list of columns hich have a detected type of VARCHAR
6
+ // then we make sure that for those columns, we don't cast an empty string to null; instead we want to keep the empty string
7
+ return `
8
+ SET VARIABLE strColumns = (SELECT list(name) FROM (SELECT unnest(Columns, recursive := true) FROM sniff_csv("${this.url}")) WHERE type = 'VARCHAR');
9
+ CREATE TABLE ${this.datasetId} AS SELECT * FROM read_csv("${this.url}",
10
+ force_not_null = getvariable('strColumns'),
11
+ auto_type_candidates = ['NULL', 'BOOLEAN', 'INTEGER', 'DOUBLE', 'DATE', 'VARCHAR']
12
+ );`
51
13
  }
52
14
  }
@@ -1,33 +1,33 @@
1
- import { DataItem, PropertyInfo } from '../model'
2
- import {
3
- fetchDataAsArrayBuffer,
4
- jsonToGeojsonFeature,
5
- processItemProperties,
6
- } from '../utils'
7
1
  import { BaseFileReader } from './base-file'
2
+ import { fetchDataAsArrayBuffer } from '../utils'
8
3
 
9
- /**
10
- * This will read the first sheet of the excel workbook and expect the first
11
- * line to contain the properties names
12
- * @param buffer
13
- */
14
- export function parseExcel(buffer: ArrayBuffer): Promise<{
15
- items: DataItem[]
16
- properties: PropertyInfo[]
17
- }> {
18
- return import('xlsx').then(({ read, utils }) => {
19
- const workbook = read(buffer)
20
- const sheet = workbook.Sheets[workbook.SheetNames[0]]
21
- let json = utils.sheet_to_json(sheet)
22
- if (!json.length) {
23
- json = []
4
+ export class ExcelReader extends BaseFileReader {
5
+ protected async getLoadQuery(): Promise<string> {
6
+ // we download the file as an array buffer first, in order to be able to check if it's an XLS file
7
+ let buffer = await fetchDataAsArrayBuffer(this.url, this.cacheEnabled)
8
+ const bufferHandle = `B${this.datasetId}`
9
+
10
+ // checking against the magic number at the beginning of XLS files, see https://en.wikipedia.org/wiki/List_of_file_signatures
11
+ const magicNumber = new Uint8Array(buffer, 0, 8) // first 8 bytes
12
+ const isXls =
13
+ Array.from(magicNumber)
14
+ .map((n) => n.toString(16).toUpperCase())
15
+ .join(' ') === 'D0 CF 11 E0 A1 B1 1A E1'
16
+
17
+ // uh oh, this is an XLS file (not supported by duckdb); convert it to CSV using the xlsx package
18
+ if (isXls) {
19
+ buffer = await import('xlsx').then(({ read, utils }) => {
20
+ const workbook = read(buffer)
21
+ const json = utils.sheet_to_json(
22
+ workbook.Sheets[workbook.SheetNames[0]]
23
+ )
24
+ return new TextEncoder().encode(JSON.stringify(json)).buffer
25
+ })
24
26
  }
25
- return processItemProperties(json.map(jsonToGeojsonFeature), true)
26
- })
27
- }
27
+ const duckDbFn = isXls ? 'read_json' : 'read_xlsx'
28
28
 
29
- export class ExcelReader extends BaseFileReader {
30
- getData() {
31
- return fetchDataAsArrayBuffer(this.url, this.cacheActive).then(parseExcel)
29
+ await this.engine.registerData(bufferHandle, new Uint8Array(buffer))
30
+ return `
31
+ CREATE TABLE ${this.datasetId} AS SELECT * FROM ${duckDbFn}("${bufferHandle}", ignore_errors = true);`
32
32
  }
33
33
  }
@@ -1,29 +1,10 @@
1
- import { DataItem, PropertyInfo } from '../model'
2
- import { fetchDataAsText, processItemProperties } from '../utils'
3
1
  import { BaseFileReader } from './base-file'
4
2
 
5
- /**
6
- * This parser supports both Geojson Feature collections or arrays
7
- * of Features
8
- * @param text
9
- */
10
- export function parseGeojson(text: string): {
11
- items: DataItem[]
12
- properties: PropertyInfo[]
13
- } {
14
- const parsed = JSON.parse(text)
15
- const features =
16
- parsed.type === 'FeatureCollection' ? parsed.features : parsed
17
- if (!Array.isArray(features)) {
18
- throw new Error(
19
- 'Could not parse GeoJSON, expected a features collection or an array of features at root level'
20
- )
21
- }
22
- return processItemProperties(features)
23
- }
24
-
25
3
  export class GeojsonReader extends BaseFileReader {
26
- getData() {
27
- return fetchDataAsText(this.url, this.cacheActive).then(parseGeojson)
4
+ async getLoadQuery() {
5
+ return `
6
+ CREATE TABLE ${this.datasetId} AS SELECT * FROM st_read("${this.url}",
7
+ allowed_drivers = ['GeoJSON']
8
+ );`
28
9
  }
29
10
  }