-
Notifications
You must be signed in to change notification settings - Fork 83
/
duckdb.js
314 lines (293 loc) · 9.92 KB
/
duckdb.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import {isArqueroTable} from "./arquero.js";
import {getArrowTableSchema, isArrowTable, loadArrow} from "./arrow.js";
import {duckdb} from "./dependencies.js";
import {FileAttachment} from "./fileAttachment.js";
import {cdn} from "./require.js";
// Adapted from https://observablehq.com/@cmudig/duckdb-client
// Copyright 2021 CMU Data Interaction Group
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
let promise;
export class DuckDBClient {
constructor(db) {
Object.defineProperties(this, {
_db: {value: db}
});
}
async queryStream(query, params) {
const connection = await this._db.connect();
let reader, batch;
try {
if (params?.length > 0) {
const statement = await connection.prepare(query);
reader = await statement.send(...params);
} else {
reader = await connection.send(query);
}
batch = await reader.next();
if (batch.done) throw new Error("missing first batch");
} catch (error) {
await connection.close();
throw error;
}
return {
schema: getArrowTableSchema(batch.value),
async *readRows() {
try {
while (!batch.done) {
yield batch.value.toArray();
batch = await reader.next();
}
} finally {
await connection.close();
}
}
};
}
async query(query, params) {
const result = await this.queryStream(query, params);
const results = [];
for await (const rows of result.readRows()) {
for (const row of rows) {
results.push(row);
}
}
results.schema = result.schema;
return results;
}
async queryRow(query, params) {
const result = await this.queryStream(query, params);
const reader = result.readRows();
try {
const {done, value} = await reader.next();
return done || !value.length ? null : value[0];
} finally {
await reader.return();
}
}
async sql(strings, ...args) {
return await this.query(strings.join("?"), args);
}
queryTag(strings, ...params) {
return [strings.join("?"), params];
}
escape(name) {
return `"${name}"`;
}
async describeTables() {
const tables = await this.query(`SHOW TABLES`);
return tables.map(({name}) => ({name}));
}
async describeColumns({table} = {}) {
const columns = await this.query(`DESCRIBE ${this.escape(table)}`);
return columns.map(({column_name, column_type, null: nullable}) => ({
name: column_name,
type: getDuckDBType(column_type),
nullable: nullable !== "NO",
databaseType: column_type
}));
}
static async of(sources = {}, config = {}) {
const db = await createDuckDB();
if (config.query?.castTimestampToDate === undefined) {
config = {...config, query: {...config.query, castTimestampToDate: true}};
}
if (config.query?.castBigIntToDouble === undefined) {
config = {...config, query: {...config.query, castBigIntToDouble: true}};
}
await db.open(config);
await Promise.all(
Object.entries(sources).map(async ([name, source]) => {
if (source instanceof FileAttachment) { // bare file
await insertFile(db, name, source);
} else if (isArrowTable(source)) { // bare arrow table
await insertArrowTable(db, name, source);
} else if (Array.isArray(source)) { // bare array of objects
await insertArray(db, name, source);
} else if (isArqueroTable(source)) {
await insertArqueroTable(db, name, source);
} else if ("data" in source) { // data + options
const {data, ...options} = source;
if (isArrowTable(data)) {
await insertArrowTable(db, name, data, options);
} else {
await insertArray(db, name, data, options);
}
} else if ("file" in source) { // file + options
const {file, ...options} = source;
await insertFile(db, name, file, options);
} else {
throw new Error(`invalid source: ${source}`);
}
})
);
return new DuckDBClient(db);
}
}
Object.defineProperty(DuckDBClient.prototype, "dialect", {
value: "duckdb"
});
async function insertFile(database, name, file, options) {
const url = await file.url();
if (url.startsWith("blob:")) {
const buffer = await file.arrayBuffer();
await database.registerFileBuffer(file.name, new Uint8Array(buffer));
} else {
await database.registerFileURL(file.name, url, 4); // duckdb.DuckDBDataProtocol.HTTP
}
const connection = await database.connect();
try {
switch (file.mimeType) {
case "text/csv":
case "text/tab-separated-values": {
return await connection.insertCSVFromPath(file.name, {
name,
schema: "main",
...options
}).catch(async (error) => {
// If initial attempt to insert CSV resulted in a conversion
// error, try again, this time treating all columns as strings.
if (error.toString().includes("Could not convert")) {
return await insertUntypedCSV(connection, file, name);
}
throw error;
});
}
case "application/json":
return await connection.insertJSONFromPath(file.name, {
name,
schema: "main",
...options
});
default:
if (/\.arrow$/i.test(file.name)) {
const buffer = new Uint8Array(await file.arrayBuffer());
return await connection.insertArrowFromIPCStream(buffer, {
name,
schema: "main",
...options
});
}
if (/\.parquet$/i.test(file.name)) {
return await connection.query(
`CREATE VIEW '${name}' AS SELECT * FROM parquet_scan('${file.name}')`
);
}
throw new Error(`unknown file type: ${file.mimeType}`);
}
} finally {
await connection.close();
}
}
async function insertUntypedCSV(connection, file, name) {
const statement = await connection.prepare(
`CREATE TABLE '${name}' AS SELECT * FROM read_csv_auto(?, ALL_VARCHAR=TRUE)`
);
return await statement.send(file.name);
}
async function insertArrowTable(database, name, table, options) {
const connection = await database.connect();
try {
await connection.insertArrowTable(table, {
name,
schema: "main",
...options
});
} finally {
await connection.close();
}
}
async function insertArqueroTable(database, name, source) {
// TODO When we have stdlib versioning and can upgrade Arquero to version 5,
// we can then call source.toArrow() directly, with insertArrowTable()
const arrow = await loadArrow();
const table = arrow.tableFromIPC(source.toArrowBuffer());
return await insertArrowTable(database, name, table);
}
async function insertArray(database, name, array, options) {
const arrow = await loadArrow();
const table = arrow.tableFromJSON(array);
return await insertArrowTable(database, name, table, options);
}
async function loadDuckDB() {
const module = await import(`${cdn}${duckdb.resolve()}`);
const bundle = await module.selectBundle({
mvp: {
mainModule: `${cdn}${duckdb.resolve("dist/duckdb-mvp.wasm")}`,
mainWorker: `${cdn}${duckdb.resolve("dist/duckdb-browser-mvp.worker.js")}`
},
eh: {
mainModule: `${cdn}${duckdb.resolve("dist/duckdb-eh.wasm")}`,
mainWorker: `${cdn}${duckdb.resolve("dist/duckdb-browser-eh.worker.js")}`
}
});
const logger = new module.ConsoleLogger();
return {module, bundle, logger};
}
async function createDuckDB() {
if (promise === undefined) promise = loadDuckDB();
const {module, bundle, logger} = await promise;
const worker = await module.createWorker(bundle.mainWorker);
const db = new module.AsyncDuckDB(logger, worker);
await db.instantiate(bundle.mainModule);
return db;
}
// https://duckdb.org/docs/sql/data_types/overview
function getDuckDBType(type) {
switch (type) {
case "BIGINT":
case "HUGEINT":
case "UBIGINT":
return "bigint";
case "DOUBLE":
case "REAL":
case "FLOAT":
return "number";
case "INTEGER":
case "SMALLINT":
case "TINYINT":
case "USMALLINT":
case "UINTEGER":
case "UTINYINT":
return "integer";
case "BOOLEAN":
return "boolean";
case "DATE":
case "TIMESTAMP":
case "TIMESTAMP WITH TIME ZONE":
return "date";
case "VARCHAR":
case "UUID":
return "string";
// case "BLOB":
// case "INTERVAL":
// case "TIME":
default:
if (/^DECIMAL\(/.test(type)) return "integer";
return "other";
}
}