Skip to content

loadDataSource #306

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/index.mjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export {default as FileAttachments, AbstractFile} from "./fileAttachment.mjs";
export {default as Library} from "./library.mjs";
export {makeQueryTemplate, arrayIsPrimitive, isDataArray, isDatabaseClient} from "./table.mjs";
export {makeQueryTemplate, loadDataSource, arrayIsPrimitive, isDataArray, isDatabaseClient} from "./table.mjs";
24 changes: 22 additions & 2 deletions src/table.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {ascending, descending, reverse} from "./array.mjs";
import {FileAttachment} from "./fileAttachment.mjs";

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

Expand Down Expand Up @@ -141,7 +142,7 @@ function isTypedArray(value) {
// __query is used by table cells; __query.sql is used by SQL cells.
export const __query = Object.assign(
async (source, operations, invalidation) => {
source = await source;
source = await loadDataSource(await source, "table");
if (isDatabaseClient(source)) return evaluateQuery(source, makeQueryTemplate(operations, source), invalidation);
if (isDataArray(source)) return __table(source, operations);
if (!source) throw new Error("missing data source");
Expand All @@ -150,12 +151,31 @@ export const __query = Object.assign(
{
sql(source, invalidation) {
return async function () {
return evaluateQuery(source, arguments, invalidation);
return evaluateQuery(await loadDataSource(await source, "sql"), arguments, invalidation);
};
}
}
);

export async function loadDataSource(source, mode) {
if (source instanceof FileAttachment) {
if (mode === "table") {
switch (source.mimeType) {
case "text/csv": return source.csv({typed: true});
case "text/tab-separated-values": return source.tsv({typed: true});
case "application/json": return source.json();
}
}
if (mode === "table" || mode === "sql") {
switch (source.mimeType) {
case "application/x-sqlite3": return source.sqlite();
}
}
throw new Error(`unsupported file type: ${source.mimeType}`);
}
return source;
}

async function evaluateQuery(source, args, invalidation) {
if (!source) throw new Error("missing data source");

Expand Down