@loaders.gl/geopackage 4.0.0-alpha.9 → 4.0.0-beta.2

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.
@@ -1,392 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.DEFAULT_SQLJS_CDN = void 0;
7
- const sql_js_1 = __importDefault(require("sql.js"));
8
- const wkt_1 = require("@loaders.gl/wkt");
9
- const gis_1 = require("@loaders.gl/gis");
10
- const proj4_1 = require("@math.gl/proj4");
11
- // We pin to the same version as sql.js that we use.
12
- // As of March 2022, versions 1.6.0, 1.6.1, and 1.6.2 of sql.js appeared not to work.
13
- exports.DEFAULT_SQLJS_CDN = 'https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.5.0/';
14
- // https://www.geopackage.org/spec121/#flags_layout
15
- const ENVELOPE_BYTE_LENGTHS = {
16
- 0: 0,
17
- 1: 32,
18
- 2: 48,
19
- 3: 48,
20
- 4: 64,
21
- // values 5-7 are invalid and _should_ never show up
22
- 5: 0,
23
- 6: 0,
24
- 7: 0
25
- };
26
- // Documentation: https://www.geopackage.org/spec130/index.html#table_column_data_types
27
- const SQL_TYPE_MAPPING = {
28
- BOOLEAN: 'bool',
29
- TINYINT: 'int8',
30
- SMALLINT: 'int16',
31
- MEDIUMINT: 'int32',
32
- INT: 'int32',
33
- INTEGER: 'int32',
34
- FLOAT: 'float32',
35
- DOUBLE: 'float64',
36
- REAL: 'float64',
37
- TEXT: 'utf8',
38
- BLOB: 'binary',
39
- DATE: 'utf8',
40
- DATETIME: 'utf8',
41
- GEOMETRY: 'binary',
42
- POINT: 'binary',
43
- LINESTRING: 'binary',
44
- POLYGON: 'binary',
45
- MULTIPOINT: 'binary',
46
- MULTILINESTRING: 'binary',
47
- MULTIPOLYGON: 'binary',
48
- GEOMETRYCOLLECTION: 'binary'
49
- };
50
- async function parseGeoPackage(arrayBuffer, options) {
51
- const { sqlJsCDN = exports.DEFAULT_SQLJS_CDN } = options?.geopackage || {};
52
- const { reproject = false, _targetCrs = 'WGS84', format = 'tables' } = options?.gis || {};
53
- const db = await loadDatabase(arrayBuffer, sqlJsCDN);
54
- const tables = listVectorTables(db);
55
- const projections = getProjections(db);
56
- // Mapping from tableName to geojson feature collection
57
- const outputTables = {
58
- shape: 'tables',
59
- tables: []
60
- };
61
- for (const table of tables) {
62
- const { table_name: tableName } = table;
63
- outputTables.tables.push({
64
- name: tableName,
65
- table: getVectorTable(db, tableName, projections, {
66
- reproject,
67
- _targetCrs
68
- })
69
- });
70
- }
71
- if (format === 'geojson') {
72
- return formatTablesAsGeojson(outputTables);
73
- }
74
- return outputTables;
75
- }
76
- exports.default = parseGeoPackage;
77
- /**
78
- * Initialize SQL.js and create database
79
- *
80
- * @param arrayBuffer input bytes
81
- * @return SQL.js database object
82
- */
83
- async function loadDatabase(arrayBuffer, sqlJsCDN) {
84
- // In Node, `locateFile` must not be passed
85
- let SQL;
86
- if (sqlJsCDN) {
87
- SQL = await (0, sql_js_1.default)({
88
- locateFile: (file) => `${sqlJsCDN}${file}`
89
- });
90
- }
91
- else {
92
- SQL = await (0, sql_js_1.default)();
93
- }
94
- return new SQL.Database(new Uint8Array(arrayBuffer));
95
- }
96
- /**
97
- * Find all vector tables in GeoPackage
98
- * This queries the `gpkg_contents` table to find a list of vector tables
99
- *
100
- * @param db GeoPackage to query
101
- * @return list of table references
102
- */
103
- function listVectorTables(db) {
104
- // The gpkg_contents table can have at least three categorical values for
105
- // data_type.
106
- // - 'features' refers to a vector geometry table
107
- // (https://www.geopackage.org/spec121/#_contents_2)
108
- // - 'tiles' refers to a raster table
109
- // (https://www.geopackage.org/spec121/#_contents_3)
110
- // - 'attributes' refers to a data table with no geometry
111
- // (https://www.geopackage.org/spec121/#_contents_4).
112
- // We hard code 'features' because for now we don't support raster data or pure attribute data
113
- // eslint-disable-next-line quotes
114
- const stmt = db.prepare("SELECT * FROM gpkg_contents WHERE data_type='features';");
115
- const vectorTablesInfo = [];
116
- while (stmt.step()) {
117
- const vectorTableInfo = stmt.getAsObject();
118
- vectorTablesInfo.push(vectorTableInfo);
119
- }
120
- return vectorTablesInfo;
121
- }
122
- /**
123
- * Load geometries from vector table
124
- *
125
- * @param db GeoPackage object
126
- * @param tableName name of vector table to query
127
- * @param projections keys are srs_id values, values are WKT strings
128
- * @returns Array of GeoJSON Feature objects
129
- */
130
- function getVectorTable(db, tableName, projections, { reproject, _targetCrs }) {
131
- const dataColumns = getDataColumns(db, tableName);
132
- const geomColumn = getGeometryColumn(db, tableName);
133
- const featureIdColumn = getFeatureIdName(db, tableName);
134
- // Get vector features from table
135
- // Don't think it's possible to parameterize the table name in SQLite?
136
- const { columns, values } = db.exec(`SELECT * FROM \`${tableName}\`;`)[0];
137
- let projection;
138
- if (reproject) {
139
- const geomColumnProjStr = projections[geomColumn.srs_id];
140
- projection = new proj4_1.Proj4Projection({
141
- from: geomColumnProjStr,
142
- to: _targetCrs
143
- });
144
- }
145
- const geojsonFeatures = [];
146
- for (const row of values) {
147
- const geojsonFeature = constructGeoJsonFeature(columns, row, geomColumn,
148
- // @ts-ignore
149
- dataColumns, featureIdColumn);
150
- geojsonFeatures.push(geojsonFeature);
151
- }
152
- const schema = getSchema(db, tableName);
153
- if (projection) {
154
- return {
155
- shape: 'object-row-table',
156
- data: (0, gis_1.transformGeoJsonCoords)(geojsonFeatures, projection.project),
157
- schema
158
- };
159
- }
160
- return { data: geojsonFeatures, schema, shape: 'object-row-table' };
161
- }
162
- /**
163
- * Find all projections defined in GeoPackage
164
- * This queries the gpkg_spatial_ref_sys table
165
- * @param db GeoPackage object
166
- * @returns mapping from srid to WKT projection string
167
- */
168
- function getProjections(db) {
169
- // Query gpkg_spatial_ref_sys to get srid: srtext mappings
170
- const stmt = db.prepare('SELECT * FROM gpkg_spatial_ref_sys;');
171
- const projectionMapping = {};
172
- while (stmt.step()) {
173
- const srsInfo = stmt.getAsObject();
174
- const { srs_id, definition } = srsInfo;
175
- projectionMapping[srs_id] = definition;
176
- }
177
- return projectionMapping;
178
- }
179
- /**
180
- * Construct single GeoJSON feature given row's data
181
- * @param columns array of ordered column identifiers
182
- * @param row array of ordered values representing row's data
183
- * @param geomColumn geometry column metadata
184
- * @param dataColumns mapping from table column names to property name
185
- * @returns GeoJSON Feature object
186
- */
187
- function constructGeoJsonFeature(columns, row, geomColumn, dataColumns, featureIdColumn) {
188
- // Find feature id
189
- const idIdx = columns.indexOf(featureIdColumn);
190
- const id = row[idIdx];
191
- // Parse geometry columns to geojson
192
- const geomColumnIdx = columns.indexOf(geomColumn.column_name);
193
- const geometry = parseGeometry(row[geomColumnIdx].buffer);
194
- const properties = {};
195
- if (dataColumns) {
196
- for (const [key, value] of Object.entries(dataColumns)) {
197
- const idx = columns.indexOf(key);
198
- // @ts-ignore TODO - Check what happens if null?
199
- properties[value] = row[idx];
200
- }
201
- }
202
- else {
203
- // Put all columns except for the feature id and geometry in properties
204
- for (let i = 0; i < columns.length; i++) {
205
- if (i === idIdx || i === geomColumnIdx) {
206
- // eslint-disable-next-line no-continue
207
- continue;
208
- }
209
- const columnName = columns[i];
210
- properties[columnName] = row[i];
211
- }
212
- }
213
- return {
214
- id,
215
- type: 'Feature',
216
- geometry,
217
- properties
218
- };
219
- }
220
- /**
221
- * Get GeoPackage version from database
222
- * @param db database
223
- * @returns version string. One of '1.0', '1.1', '1.2'
224
- */
225
- // @ts-ignore
226
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
227
- function getGeopackageVersion(db) {
228
- const textDecoder = new TextDecoder();
229
- // Read application id from SQLite metadata
230
- const applicationIdQuery = db.exec('PRAGMA application_id;')[0];
231
- const applicationId = applicationIdQuery.values[0][0];
232
- // Convert 4-byte signed int32 application id to text
233
- const buffer = new ArrayBuffer(4);
234
- const view = new DataView(buffer);
235
- view.setInt32(0, Number(applicationId));
236
- const versionString = textDecoder.decode(buffer);
237
- if (versionString === 'GP10') {
238
- return '1.0';
239
- }
240
- if (versionString === 'GP11') {
241
- return '1.1';
242
- }
243
- // If versionString is GPKG, then read user_version
244
- const userVersionQuery = db.exec('PRAGMA user_version;')[0];
245
- const userVersionInt = userVersionQuery.values[0][0];
246
- if (userVersionInt && typeof userVersionInt === 'number' && userVersionInt < 10300) {
247
- return '1.2';
248
- }
249
- return null;
250
- }
251
- /**
252
- * Find name of feature id column in table
253
- * The feature ID is the primary key of the table.
254
- * http://www.geopackage.org/spec121/#feature_user_tables
255
- *
256
- * @param db database
257
- * @param tableName name of table
258
- * @return name of feature id column
259
- */
260
- function getFeatureIdName(db, tableName) {
261
- // Again, not possible to parameterize table name?
262
- const stmt = db.prepare(`PRAGMA table_info(\`${tableName}\`)`);
263
- while (stmt.step()) {
264
- const pragmaTableInfo = stmt.getAsObject();
265
- const { name, pk } = pragmaTableInfo;
266
- if (pk) {
267
- return name;
268
- }
269
- }
270
- // Is it guaranteed for there always to be at least one primary key column in the table?
271
- return null;
272
- }
273
- /**
274
- * Parse geometry buffer
275
- * GeoPackage vector geometries are slightly extended past the WKB standard
276
- * See: https://www.geopackage.org/spec121/#gpb_format
277
- *
278
- * @param arrayBuffer geometry buffer
279
- * @return GeoJSON geometry (in original CRS)
280
- */
281
- function parseGeometry(arrayBuffer) {
282
- const view = new DataView(arrayBuffer);
283
- const { envelopeLength, emptyGeometry } = parseGeometryBitFlags(view.getUint8(3));
284
- // A Feature object has a member with the name "geometry". The value of the
285
- // geometry member SHALL be either a Geometry object as defined above or, in
286
- // the case that the Feature is unlocated, a JSON null value.
287
- /** @see https://tools.ietf.org/html/rfc7946#section-3.2 */
288
- if (emptyGeometry) {
289
- return null;
290
- }
291
- // Do I need to find the srid here? Is it necessarily the same for every
292
- // geometry in a table?
293
- // const srid = view.getInt32(4, littleEndian);
294
- // 2 byte magic, 1 byte version, 1 byte flags, 4 byte int32 srid
295
- const wkbOffset = 8 + envelopeLength;
296
- // Loaders should not depend on `core` and the context passed to the main loader doesn't include a
297
- // `parseSync` option, so instead we call parseSync directly on WKBLoader
298
- const binaryGeometry = wkt_1.WKBLoader.parseSync(arrayBuffer.slice(wkbOffset));
299
- return (0, gis_1.binaryToGeometry)(binaryGeometry);
300
- }
301
- /**
302
- * Parse geometry header flags
303
- * https://www.geopackage.org/spec121/#flags_layout
304
- *
305
- * @param byte uint8 number representing flags
306
- * @return object representing information from bit flags
307
- */
308
- function parseGeometryBitFlags(byte) {
309
- // Are header values little endian?
310
- const envelopeValue = (byte & 0b00001110) / 2;
311
- // TODO: Not sure the best way to handle this. Throw an error if envelopeValue outside 0-7?
312
- const envelopeLength = ENVELOPE_BYTE_LENGTHS[envelopeValue];
313
- return {
314
- littleEndian: Boolean(byte & 0b00000001),
315
- envelopeLength,
316
- emptyGeometry: Boolean(byte & 0b00010000),
317
- extendedGeometryType: Boolean(byte & 0b00100000)
318
- };
319
- }
320
- /**
321
- * Find geometry column in given vector table
322
- *
323
- * @param db GeoPackage object
324
- * @param tableName Name of vector table
325
- * @returns Array of geometry column definitions
326
- */
327
- function getGeometryColumn(db, tableName) {
328
- const stmt = db.prepare('SELECT * FROM gpkg_geometry_columns WHERE table_name=:tableName;');
329
- stmt.bind({ ':tableName': tableName });
330
- // > Requirement 30
331
- // > A feature table SHALL have only one geometry column.
332
- // https://www.geopackage.org/spec121/#feature_user_tables
333
- // So we should need one and only one step, given that we use the WHERE clause in the SQL query
334
- // above
335
- stmt.step();
336
- const geometryColumn = stmt.getAsObject();
337
- return geometryColumn;
338
- }
339
- /**
340
- * Find property columns in given vector table
341
- * @param db GeoPackage object
342
- * @param tableName Name of vector table
343
- * @returns Mapping from table column names to property name
344
- */
345
- function getDataColumns(db, tableName) {
346
- // gpkg_data_columns is not required to exist
347
- // https://www.geopackage.org/spec121/#extension_schema
348
- let stmt;
349
- try {
350
- stmt = db.prepare('SELECT * FROM gpkg_data_columns WHERE table_name=:tableName;');
351
- }
352
- catch (error) {
353
- if (error.message.includes('no such table')) {
354
- return null;
355
- }
356
- throw error;
357
- }
358
- stmt.bind({ ':tableName': tableName });
359
- // Convert DataColumnsRow object this to a key-value {column_name: name}
360
- const result = {};
361
- while (stmt.step()) {
362
- const column = stmt.getAsObject();
363
- const { column_name, name } = column;
364
- result[column_name] = name || null;
365
- }
366
- return result;
367
- }
368
- /**
369
- * Get arrow schema
370
- * @param db GeoPackage object
371
- * @param tableName table name
372
- * @returns Arrow-like Schema
373
- */
374
- function getSchema(db, tableName) {
375
- const stmt = db.prepare(`PRAGMA table_info(\`${tableName}\`)`);
376
- const fields = [];
377
- while (stmt.step()) {
378
- const pragmaTableInfo = stmt.getAsObject();
379
- const { name, type: sqlType, notnull } = pragmaTableInfo;
380
- const type = SQL_TYPE_MAPPING[sqlType];
381
- const field = { name, type, nullable: !notnull };
382
- fields.push(field);
383
- }
384
- return { fields, metadata: {} };
385
- }
386
- function formatTablesAsGeojson(tables) {
387
- const geojsonMap = {};
388
- for (const table of tables.tables) {
389
- geojsonMap[table.name] = table.table.data;
390
- }
391
- return geojsonMap;
392
- }
package/dist/lib/types.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });