66 lines · 2.1 KB
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<T>(sql: string, ...params: D1Value[]): Promise<T | null> {
  return stmt(sql, ...params).first<T>();
}

export async function all<T>(sql: string, ...params: D1Value[]): Promise<T[]> {
  const result = await stmt(sql, ...params).all<T>();
  return result.results;
}

export async function run(sql: string, ...params: D1Value[]): Promise<D1Result> {
  return stmt(sql, ...params).run();
}

export async function batch(statements: D1PreparedStatement[]): Promise<D1Result[]> {
  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<T>(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;
}

export type ReadSession = {