import { env } from "cloudflare:workers"; type D1Value = string | number | null; export function stmt(sql: string, ...params: D1Value[]): D1PreparedStatement { return env.DB.prepare(sql).bind(...params); } export async function first(sql: string, ...params: D1Value[]): Promise { return stmt(sql, ...params).first(); } export async function all(sql: string, ...params: D1Value[]): Promise { const result = await stmt(sql, ...params).all(); return result.results; } export async function run(sql: string, ...params: D1Value[]): Promise { return stmt(sql, ...params).run(); } export async function batch(statements: D1PreparedStatement[]): Promise { if (statements.length === 0) return []; return env.DB.batch(statements); } export function placeholders(count: number): string { return Array.from({ length: count }, () => "?").join(", "); } /** D1 allows at most 100 bound parameters per statement; keep IN-lists well below that. */ export const MAX_IN_LIST = 90; export function chunks(items: T[], size = MAX_IN_LIST): T[][] { const out: T[][] = []; for (let index = 0; index < items.length; index += size) out.push(items.slice(index, index + size)); return out; }