import { API_URL } from "https://esm.town/v/std/API_URL";
import { LibsqlError, type ResultSet, type Row, type TransactionMode } from "npm:@libsql/client";
import { z } from "npm:zod";
export const sqlite = {
execute,
batch,
};
async function execute(statement: InStatement, args?: InArgs): Promise<ResultSet> {
const res = await fetch(`${API_URL}/v1/sqlite/execute`, {
method: "POST",
headers: {
Authorization: `Bearer ${Deno.env.get("valtown")}`,
},
body: JSON.stringify({ statement: normalizeStatement(statement, args) }),
});
if (!res.ok) {
throw createResError(await res.text());
}
const resultSet = await res.json();
return upgradeResultSet(resultSet);
}
async function batch(statements: InStatement[], mode?: TransactionMode): Promise<ResultSet[]> {
const res = await fetch(`${API_URL}/v1/sqlite/batch`, {
method: "POST",
headers: {
Authorization: `Bearer ${Deno.env.get("valtown")}`,
},
body: JSON.stringify({ statements: statements.map(s => normalizeStatement(s)), mode }),
});
if (!res.ok) {
throw createResError(await res.text());
}
const resultSets = await res.json();
return resultSets.map(upgradeResultSet);
}
function createResError(body: string) {
try {
const e = zLibsqlError.parse(JSON.parse(body));
const msg = e.message.replace(e.code, "").replace(/^:\s+/, "");
return new LibsqlError(msg, e.code, e.rawCode);
} catch (_) {
}
return new Error(body);
}
interface ImpoverishedResultSet extends ResultSet {
rows: any[];
}
function normalizeStatement(statement: InStatement, args?: InArgs) {
if (Array.isArray(statement)) {
return normalizeStatement(statement[0], statement[1]);
}
if (typeof statement === "string") {
if (args) {
return { sql: statement, args };
} else return statement;
}
else if (typeof statement === "object") {
if (statement.args) {
return statement;
}