import { Statement, type StatementInstance } from "https://esm.town/v/postpostscript/sqliteBuilder";
import { sqliteDump, type SqliteDumpOptions } from "https://esm.town/v/postpostscript/sqliteDump";
import { createSqlite } from "https://esm.town/v/postpostscript/sqliteWasm";
import type { MaybePromise } from "https://esm.town/v/postpostscript/typeUtils";
import { blob as blobAPI } from "https://esm.town/v/std/blob";
import { type InStatement, sqlite as sqliteAPI } from "https://esm.town/v/std/sqlite";
import { type ResultSet } from "npm:@libsql/client";
export async function sqliteBackup(
{ name = `backup:sqlite:${new Date().getTime()}`, blob = blobAPI, dumpOptions = {} }: SqliteBackupOptions = {},
) {
return {
name,
content: await sqliteToBlob({
name,
blob,
dumpOptions,
}),
};
}
export async function sqliteToBlob(
{ name, dumpOptions, blob = blobAPI }: SqliteToBlobOptions,
) {
const statements = await sqliteDump(dumpOptions);
await blob.setJSON(name, statements);
return JSON.stringify(statements);
}
export async function sqliteFromBlob(
{ name, blob = blobAPI }: SqliteFromBlobOptions,
) {
const statements = await blob.getJSON(name);
if (!statements) {
throw new Error(`blob ${name} does not exist`);
}
const sqlite = createSqlite();
sqlite.batch(await statements);
return sqlite;
}
function statementWrites(statement: InStatement) {
const sql = typeof statement === "string"
? statement
: statement.sql;
return !!` ${sql} `.match(/\s(INSERT|UPDATE|DELETE|CREATE)\s/i);
}
export type SqliteBackupOptions = {
name?: string;
dumpOptions?: SqliteDumpOptions;
blob?: {
setJSON: (...args: any[]) => any;
getJSON: (...args: any[]) => any;
};
};
export type SqliteToBlobOptions = {
name: string;
dumpOptions: SqliteDumpOptions;
blob?: {