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
import { type InStatement, type InValue, type ResultSet, sqlite } from "https://esm.town/v/std/sqlite?v=5";
let batch: { statement: InStatement; promise: ReturnType<typeof Promise.withResolvers<ResultSet>> }[] | null = null;
async function flush() {
const currentBatch = batch;
batch = null;
try {
const results = await sqlite.batch(currentBatch.map(e => e.statement));
for (let i = 0; i < currentBatch.length; i++) {
currentBatch[i].promise.resolve(results[i]);
}
} catch (e) {
for (const query of currentBatch) {
query.promise.reject(e);
}
}
}
const joined = new WeakMap<TemplateStringsArray, string>();
function cachedJoin(strings) {
let result = joined.get(strings);
if (typeof result === "string") {
return result;
}
result = strings.join("?");
joined.set(strings, result);
return result;
}
export function sql(query: TemplateStringsArray, ...args: InValue[]): Promise<ResultSet> {
if (batch === null) {
setTimeout(flush);
batch = [];
}
const promise = Promise.withResolvers<ResultSet>();
batch.push({
statement: {
sql: cachedJoin(query),
args,
},
promise,
});
return promise.promise;
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
March 26, 2024