import sql from "k6/x/sql";
import driver from "k6/x/sql/driver/postgres";
import {
  allMatch,
  contains,
  defaultOptions,
  isSorted,
} from "./checks.js";

export { allMatch, contains, defaultOptions, isSorted };

export function openDb() {
  const url = __ENV.DATABASE_URL;
  if (!url) {
    throw new Error("DATABASE_URL env var required");
  }
  return sql.open(driver, url);
}

export function truncate(db, ...tables) {
  if (tables.length === 0) return;
  db.exec(`TRUNCATE ${tables.join(", ")} CASCADE`);
}

export function createDalContext(db = openDb()) {
  return {
    db,
    truncate(...tables) {
      return truncate(db, ...tables);
    },
  };
}
