import { env } from "cloudflare:workers";
import { countD1, countD1Rows, timed } from "./perf";
type D1Value = string | number | null;
export function stmt(sql: string, ...params: D1Value[]): D1PreparedStatement {
return env.DB.prepare(sql).bind(...params);
}
const count = (ms: number) => countD1(ms);
export async function first<T>(sql: string, ...params: D1Value[]): Promise<T | null> {
return timed(count, () => stmt(sql, ...params).first<T>());
}
function rows(result: D1Result): void {
countD1Rows(result.meta?.rows_read ?? 0, result.meta?.rows_written ?? 0);
}
export async function all<T>(sql: string, ...params: D1Value[]): Promise<T[]> {
const result = await timed(count, () => stmt(sql, ...params).all<T>());
rows(result);
return result.results;
}
export async function run(sql: string, ...params: D1Value[]): Promise<D1Result> {
const result = await timed(count, () => stmt(sql, ...params).run());
rows(result);
return result;
}
export async function batch(statements: D1PreparedStatement[]): Promise<D1Result[]> {
if (statements.length === 0) return [];
const results = await timed(count, () => env.DB.batch(statements));
for (const result of results) rows(result);
return results;
}
export function placeholders(count: number): string {
return Array.from({ length: count }, () => "?").join(", ");