Skip to content

Commit 0911e80

Browse files
authored
loadDataSource (#306)
1 parent d5753d0 commit 0911e80

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

src/index.mjs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
export {default as FileAttachments, AbstractFile} from "./fileAttachment.mjs";
22
export {default as Library} from "./library.mjs";
3-
export {makeQueryTemplate, arrayIsPrimitive, isDataArray, isDatabaseClient} from "./table.mjs";
3+
export {makeQueryTemplate, loadDataSource, arrayIsPrimitive, isDataArray, isDatabaseClient} from "./table.mjs";

src/table.mjs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {ascending, descending, reverse} from "./array.mjs";
2+
import {FileAttachment} from "./fileAttachment.mjs";
23

34
const nChecks = 20; // number of values to check in each array
45

@@ -141,7 +142,7 @@ function isTypedArray(value) {
141142
// __query is used by table cells; __query.sql is used by SQL cells.
142143
export const __query = Object.assign(
143144
async (source, operations, invalidation) => {
144-
source = await source;
145+
source = await loadDataSource(await source, "table");
145146
if (isDatabaseClient(source)) return evaluateQuery(source, makeQueryTemplate(operations, source), invalidation);
146147
if (isDataArray(source)) return __table(source, operations);
147148
if (!source) throw new Error("missing data source");
@@ -150,12 +151,31 @@ export const __query = Object.assign(
150151
{
151152
sql(source, invalidation) {
152153
return async function () {
153-
return evaluateQuery(source, arguments, invalidation);
154+
return evaluateQuery(await loadDataSource(await source, "sql"), arguments, invalidation);
154155
};
155156
}
156157
}
157158
);
158159

160+
export async function loadDataSource(source, mode) {
161+
if (source instanceof FileAttachment) {
162+
if (mode === "table") {
163+
switch (source.mimeType) {
164+
case "text/csv": return source.csv({typed: true});
165+
case "text/tab-separated-values": return source.tsv({typed: true});
166+
case "application/json": return source.json();
167+
}
168+
}
169+
if (mode === "table" || mode === "sql") {
170+
switch (source.mimeType) {
171+
case "application/x-sqlite3": return source.sqlite();
172+
}
173+
}
174+
throw new Error(`unsupported file type: ${source.mimeType}`);
175+
}
176+
return source;
177+
}
178+
159179
async function evaluateQuery(source, args, invalidation) {
160180
if (!source) throw new Error("missing data source");
161181

0 commit comments

Comments
 (0)