import { expect, test } from "bun:test"; import { SchemaError } from "../src/error"; import { Prequel, Table } from "../src/index"; interface User { user_id: number; name: string; } test("constructor", () => { const pq = new Prequel(); const users = pq.table("Users", { user_id: { type: "INTEGER", primary: true, }, name: "TEXT", }); users.insertPartial({ name: "Yondu" }); expect(users.findAll().length).toBe(1); }); test(".hasTable() knows if a table exists in the DB", () => { const pq = new Prequel(); expect(pq.hasTable("Users")).toBeFalse(); expect(pq.hasTable("Notfound")).toBeFalse(); pq.table("Users", { user_id: { type: "INTEGER", primary: true, }, name: "TEXT", }); expect(pq.hasTable("Users")).toBeTrue(); expect(pq.hasTable("Notfound")).toBeFalse(); }); test(".table() creates and attaches a table", () => { const pq = new Prequel(); // Already has one table because of KV expect(Object.keys(pq.tables)).toHaveLength(1); const table = pq.table("Users", { user_id: { type: "INTEGER", primary: true, }, name: "TEXT", }); expect(Object.keys(pq.tables)).toHaveLength(2); expect(Object.values(pq.tables)).toContain(table); }); test(".table() throws when creating a duplicate table", () => { const pq = new Prequel(); pq.table("Users", { user_id: { type: "INTEGER", primary: true, }, name: "TEXT", }); const oopsie = () => { pq.table("Users", { user_id: { type: "INTEGER", primary: true, }, name: "TEXT", }); }; expect(oopsie).toThrow(SchemaError); }); test(".attachTable() attaches a table", () => { const pq = new Prequel(); const table = new Table(pq.db, "Users", { user_id: { type: "INTEGER", primary: true, }, name: "TEXT", }); expect(pq.hasTable("Users")).toBeFalse(); pq.attachTable(table); expect(pq.hasTable("Users")).toBeTrue(); expect(Object.values(pq.tables)).toContain(table); }); test(".attachTable() throws on duplicate table names", () => { const pq = new Prequel(); pq.table("Users", { user_id: { type: "INTEGER", primary: true, }, name: "TEXT", }); const secondTable = new Table(pq.db, "Users", { user_id: { type: "INTEGER", primary: true, }, name: "TEXT", }); const doAttachment = () => { pq.attachTable(secondTable); }; expect(doAttachment).toThrow(SchemaError); }); test("kv store can set and retrieve arbitrary values", () => { const pq = new Prequel(); pq.kv.put("answer", 42); pq.kv.put<{ enabled: boolean }>("config", { enabled: true }); pq.kv.put("list", ["a", "b", "c"]); expect(pq.kv.get("answer")).toEqual(42); expect(pq.kv.get<{ enabled: boolean }>("config")).toEqual({ enabled: true }); expect(pq.kv.get("list")).toEqual(["a", "b", "c"]); });