Refactor Study Desk application structure

This commit is contained in:
Elijah 2026-08-07 19:31:23 -07:00
parent faaccf8a7e
commit 089439ed90
145 changed files with 8087 additions and 3412 deletions

View file

@ -0,0 +1,41 @@
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { assertDisposableTestDatabase } from "./testDatabase";
const cleanup: string[] = [];
afterEach(() => {
for (const directory of cleanup.splice(0)) {
rmSync(directory, { recursive: true, force: true });
}
});
describe("assertDisposableTestDatabase", () => {
it("accepts a new uniquely named test database", () => {
const directory = mkdtempSync(path.join(tmpdir(), "study-db-safety-"));
cleanup.push(directory);
const target = path.join(directory, "unique.test.db");
expect(assertDisposableTestDatabase(`file:${target}`)).toBe(path.resolve(target));
});
it.each(["file:./dev.db", "file:/app/data/study.db"])(
"rejects protected database path %s",
(databaseUrl) => {
expect(() => assertDisposableTestDatabase(databaseUrl)).toThrow(
"Refusing to use non-disposable database"
);
}
);
it("rejects an existing database even when its name looks like a test", () => {
const directory = mkdtempSync(path.join(tmpdir(), "study-db-safety-"));
cleanup.push(directory);
const target = path.join(directory, "existing.test.db");
writeFileSync(target, "not disposable");
expect(() => assertDisposableTestDatabase(`file:${target}`)).toThrow(
"Refusing to use non-disposable database"
);
});
});

View file

@ -0,0 +1,107 @@
import { createHash, randomUUID } from "node:crypto";
import {
existsSync,
mkdirSync,
readFileSync,
readdirSync,
rmSync,
} from "node:fs";
import path from "node:path";
import Database from "better-sqlite3";
export interface DisposableDatabase {
databaseUrl: string;
databasePath: string;
directory: string;
}
function pathFromDatabaseUrl(databaseUrl: string, cwd = process.cwd()) {
if (!databaseUrl.startsWith("file:")) {
throw new Error("Tests require a file: SQLite DATABASE_URL");
}
const withoutScheme = databaseUrl.slice("file:".length).split("?")[0];
return path.resolve(cwd, withoutScheme);
}
export function assertDisposableTestDatabase(databaseUrl: string) {
const databasePath = pathFromDatabaseUrl(databaseUrl);
const normalized = databasePath.replaceAll("\\", "/").toLowerCase();
if (
normalized.endsWith("/dev.db") ||
normalized === "/app/data/study.db" ||
existsSync(databasePath) ||
!path.basename(databasePath).includes(".test.")
) {
throw new Error(`Refusing to use non-disposable database: ${databasePath}`);
}
return databasePath;
}
export function createDisposableDatabase(): DisposableDatabase {
const directory = path.join(
process.cwd(),
".test-databases",
`study-desk-tests-${randomUUID()}`
);
mkdirSync(directory, { recursive: true });
const databasePath = path.join(directory, `${randomUUID()}.test.db`);
const relativePath = path.relative(process.cwd(), databasePath).replaceAll("\\", "/");
const databaseUrl = `file:./${relativePath}`;
assertDisposableTestDatabase(databaseUrl);
return { databaseUrl, databasePath, directory };
}
export function applyCommittedMigrations(
database: DisposableDatabase,
options: { exclude?: string[]; through?: string } = {}
) {
assertDisposableTestDatabase(database.databaseUrl);
const migrationRoot = path.join(process.cwd(), "prisma", "migrations");
const migrationNames = readdirSync(migrationRoot, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.filter((name) => !(options.exclude ?? []).includes(name))
.filter((name) => !options.through || name <= options.through)
.sort();
const client = new Database(database.databasePath);
try {
client.pragma("foreign_keys = ON");
client.exec(`
CREATE TABLE "_prisma_migrations" (
"id" TEXT NOT NULL PRIMARY KEY,
"checksum" TEXT NOT NULL,
"finished_at" DATETIME,
"migration_name" TEXT NOT NULL,
"logs" TEXT,
"rolled_back_at" DATETIME,
"started_at" DATETIME NOT NULL DEFAULT current_timestamp,
"applied_steps_count" INTEGER NOT NULL DEFAULT 0
);
`);
const recordMigration = client.prepare(`
INSERT INTO "_prisma_migrations"
("id", "checksum", "finished_at", "migration_name", "applied_steps_count")
VALUES (?, ?, current_timestamp, ?, 1)
`);
for (const migrationName of migrationNames) {
const sql = readFileSync(
path.join(migrationRoot, migrationName, "migration.sql"),
"utf8"
);
client.transaction(() => {
client.exec(sql);
recordMigration.run(
randomUUID(),
createHash("sha256").update(sql).digest("hex"),
migrationName
);
})();
}
} finally {
client.close();
}
}
export function disposeDisposableDatabase(database: DisposableDatabase) {
rmSync(database.directory, { recursive: true, force: true });
}

View file

@ -0,0 +1,151 @@
import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
import path from "node:path";
import Database from "better-sqlite3";
import { afterEach, describe, expect, it } from "vitest";
import {
applyCommittedMigrations,
createDisposableDatabase,
disposeDisposableDatabase,
type DisposableDatabase,
} from "./helpers/testDatabase";
const GROUP_MIGRATION = "20260807090000_add_material_groups";
const databases: DisposableDatabase[] = [];
afterEach(() => {
for (const database of databases.splice(0)) {
disposeDisposableDatabase(database);
}
});
function create(options: { excludeGroup?: boolean } = {}) {
const database = createDisposableDatabase();
databases.push(database);
applyCommittedMigrations(
database,
options.excludeGroup ? { through: "20260714010000_add_arcade" } : {}
);
return database;
}
function inspect(database: DisposableDatabase) {
const result = spawnSync(
process.execPath,
[path.join(process.cwd(), "scripts", "migration-preflight.mjs")],
{
cwd: process.cwd(),
env: { ...process.env, DATABASE_URL: database.databaseUrl },
encoding: "utf8",
}
);
return { status: result.status, output: JSON.parse(result.stdout) };
}
describe("material group migration preflight", () => {
it("preserves populated pre-group rows and relationships", () => {
const database = create({ excludeGroup: true });
const client = new Database(database.databasePath);
try {
client.pragma("foreign_keys = ON");
client.prepare('INSERT INTO "Class" ("id", "slug", "name") VALUES (?, ?, ?)').run("class-1", "class", "Class");
client.prepare('INSERT INTO "Deck" ("id", "classId", "name") VALUES (?, ?, ?)').run("deck-1", "class-1", "Deck");
client.prepare('INSERT INTO "QuizSet" ("id", "classId", "name") VALUES (?, ?, ?)').run("quiz-1", "class-1", "Quiz");
client.prepare('INSERT INTO "ShareLink" ("id", "targetType", "deckId") VALUES (?, ?, ?)').run("share-1", "DECK", "deck-1");
client.exec(readFileSync(
path.join(process.cwd(), "prisma", "migrations", GROUP_MIGRATION, "migration.sql"),
"utf8"
));
expect(client.prepare('SELECT COUNT(*) AS count FROM "Deck"').get()).toEqual({ count: 1 });
expect(client.prepare('SELECT COUNT(*) AS count FROM "QuizSet"').get()).toEqual({ count: 1 });
expect(client.prepare('SELECT "deckId", "groupId" FROM "ShareLink" WHERE "id" = ?').get("share-1")).toEqual({
deckId: "deck-1",
groupId: null,
});
expect(client.pragma("foreign_key_check")).toEqual([]);
} finally {
client.close();
}
});
it("classifies a tracked pre-group database for normal apply", () => {
expect(inspect(create({ excludeGroup: true }))).toMatchObject({
status: 0,
output: { classification: "APPLY", priorHistoryComplete: true },
});
});
it("classifies an exact schema-pushed database for explicit adoption", () => {
const database = create({ excludeGroup: true });
const client = new Database(database.databasePath);
client.exec(readFileSync(
path.join(process.cwd(), "prisma", "migrations", GROUP_MIGRATION, "migration.sql"),
"utf8"
));
client.close();
expect(inspect(database)).toMatchObject({
status: 0,
output: {
classification: "ADOPT",
priorHistoryComplete: true,
exactSchema: { adoptedGroup: true },
},
});
});
it("rejects a partial schema without modifying it", () => {
const database = create();
const client = new Database(database.databasePath);
client.exec('DROP INDEX "ShareLink_groupId_key"');
const before = client
.prepare("SELECT COUNT(*) AS count FROM _prisma_migrations")
.get() as { count: number };
client.close();
expect(inspect(database)).toMatchObject({
status: 2,
output: { classification: "CONFLICT" },
});
const verification = new Database(database.databasePath, { readonly: true });
const after = verification
.prepare("SELECT COUNT(*) AS count FROM _prisma_migrations")
.get() as { count: number };
verification.close();
expect(after.count).toBe(before.count);
});
it("does not accept the source database itself as the adoption backup", () => {
const database = create({ excludeGroup: true });
const client = new Database(database.databasePath);
client.exec(readFileSync(
path.join(process.cwd(), "prisma", "migrations", GROUP_MIGRATION, "migration.sql"),
"utf8"
));
client.close();
const result = spawnSync(
process.execPath,
[
path.join(process.cwd(), "scripts", "migration-preflight.mjs"),
"--resolve",
"--backup",
database.databasePath,
],
{
cwd: process.cwd(),
env: { ...process.env, DATABASE_URL: database.databaseUrl },
encoding: "utf8",
}
);
expect(result.status).not.toBe(0);
expect(result.stderr).toContain("separate database file");
});
it("recognizes an already applied exact schema", () => {
expect(inspect(create())).toMatchObject({
status: 0,
output: { classification: "CURRENT" },
});
});
});

View file

@ -0,0 +1,40 @@
import Database from "better-sqlite3";
import path from "node:path";
import { describe, expect, it } from "vitest";
function testDatabasePath() {
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl?.startsWith("file:./")) {
throw new Error("Disposable test DATABASE_URL was not provided");
}
return path.resolve(process.cwd(), databaseUrl.slice("file:".length));
}
describe("committed migration chain", () => {
it("creates material groups and all expected group relationships", () => {
const database = new Database(testDatabasePath(), { readonly: true });
try {
const tables = database
.prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
.all() as Array<{ name: string }>;
expect(tables.map((table) => table.name)).toContain("MaterialGroup");
for (const table of ["Deck", "QuizSet", "ShareLink"]) {
const columns = database.pragma(`table_info(${table})`) as Array<{
name: string;
}>;
expect(columns.map((column) => column.name)).toContain("groupId");
}
const groupIndexes = database.pragma("index_list(ShareLink)") as Array<{
name: string;
unique: number;
}>;
expect(groupIndexes).toContainEqual(
expect.objectContaining({ name: "ShareLink_groupId_key", unique: 1 })
);
} finally {
database.close();
}
});
});

View file

@ -0,0 +1,174 @@
import { copyFileSync, readFileSync } from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import Database from "better-sqlite3";
import { afterEach, describe, expect, it } from "vitest";
import {
applyCommittedMigrations,
createDisposableDatabase,
disposeDisposableDatabase,
type DisposableDatabase,
} from "./helpers/testDatabase";
const BEFORE_GROUP = "20260714010000_add_arcade";
const GROUP_MIGRATION = "20260807090000_add_material_groups";
const prismaCli = path.join(process.cwd(), "node_modules", "prisma", "build", "index.js");
const databases: DisposableDatabase[] = [];
function createDatabase() {
const database = createDisposableDatabase();
databases.push(database);
return database;
}
function absoluteDatabaseUrl(database: DisposableDatabase) {
return `file:${database.databasePath.replaceAll("\\", "/")}`;
}
function prisma(database: DisposableDatabase, ...args: string[]) {
return spawnSync(process.execPath, [prismaCli, ...args], {
cwd: process.cwd(),
env: { ...process.env, DATABASE_URL: absoluteDatabaseUrl(database) },
encoding: "utf8",
});
}
afterEach(() => {
for (const database of databases.splice(0)) disposeDisposableDatabase(database);
});
describe.skipIf(process.platform === "win32")("native Prisma migration deployment", () => {
it("deploys the committed chain to a fresh database with no schema drift", () => {
const database = createDatabase();
const deploy = prisma(database, "migrate", "deploy");
expect(deploy.status, `${deploy.stdout}\n${deploy.stderr}`).toBe(0);
const diff = prisma(
database,
"migrate",
"diff",
"--from-config-datasource",
"--to-schema",
"prisma/schema.prisma",
"--exit-code"
);
expect(diff.status, `${diff.stdout}\n${diff.stderr}`).toBe(0);
expect(diff.stdout).toContain("No difference detected");
}, 60_000);
it("preserves populated pre-group data while deploying later migrations", () => {
const database = createDatabase();
applyCommittedMigrations(database, { through: BEFORE_GROUP });
const sqlite = new Database(database.databasePath);
try {
sqlite.pragma("foreign_keys = ON");
sqlite.exec(`
INSERT INTO "Class" ("id", "slug", "name", "sortOrder")
VALUES ('class-before', 'class-before', 'Before', 0);
INSERT INTO "Deck" ("id", "classId", "name", "sortOrder")
VALUES ('deck-before', 'class-before', 'Preserved Deck', 0);
INSERT INTO "Flashcard" ("id", "deckId", "front", "back", "sortOrder")
VALUES ('card-before', 'deck-before', 'Front', 'Back', 0);
`);
} finally {
sqlite.close();
}
const deploy = prisma(database, "migrate", "deploy");
expect(deploy.status, `${deploy.stdout}\n${deploy.stderr}`).toBe(0);
const restored = new Database(database.databasePath, { readonly: true });
try {
expect(
restored
.prepare(`
SELECT d.name AS deckName, f.front AS front
FROM "Deck" d JOIN "Flashcard" f ON f."deckId" = d.id
WHERE d.id = 'deck-before'
`)
.get()
).toEqual({ deckName: "Preserved Deck", front: "Front" });
expect(restored.pragma("integrity_check", { simple: true })).toBe("ok");
expect(restored.pragma("foreign_key_check")).toEqual([]);
} finally {
restored.close();
}
}, 60_000);
it("adopts an exact schema-pushed group database only with a verified backup", () => {
const database = createDatabase();
applyCommittedMigrations(database, { through: BEFORE_GROUP });
const sqlite = new Database(database.databasePath);
try {
sqlite.exec(
readFileSync(
path.join("prisma", "migrations", GROUP_MIGRATION, "migration.sql"),
"utf8"
)
);
sqlite.prepare(
`INSERT INTO "Class" ("id", "slug", "name", "sortOrder")
VALUES ('class-adopted', 'class-adopted', 'Adopted Class', 0)`
).run();
sqlite.prepare(
`INSERT INTO "MaterialGroup" ("id", "classId", "type", "name", "sortOrder")
VALUES ('group-adopted', 'class-adopted', 'FLASHCARD', 'Adopted', 0)`
).run();
} finally {
sqlite.close();
}
const backupPath = path.join(database.directory, "verified-backup.test.db");
copyFileSync(database.databasePath, backupPath);
const preflight = spawnSync(
process.execPath,
["scripts/migration-preflight.mjs", "--resolve", "--backup", backupPath],
{
cwd: process.cwd(),
env: { ...process.env, DATABASE_URL: absoluteDatabaseUrl(database) },
encoding: "utf8",
}
);
expect(preflight.status, `${preflight.stdout}\n${preflight.stderr}`).toBe(0);
expect(preflight.stdout).toContain('"classification": "ADOPT"');
const deploy = prisma(database, "migrate", "deploy");
expect(deploy.status, `${deploy.stdout}\n${deploy.stderr}`).toBe(0);
const restored = new Database(database.databasePath, { readonly: true });
try {
expect(
restored.prepare(
`SELECT name FROM "MaterialGroup" WHERE id = 'group-adopted'`
).get()
).toEqual({ name: "Adopted" });
} finally {
restored.close();
}
}, 60_000);
it("refuses a partial group schema instead of repairing it", () => {
const database = createDatabase();
applyCommittedMigrations(database, { through: BEFORE_GROUP });
const sqlite = new Database(database.databasePath);
try {
sqlite.exec('CREATE TABLE "MaterialGroup" ("id" TEXT NOT NULL PRIMARY KEY);');
} finally {
sqlite.close();
}
const preflight = spawnSync(process.execPath, ["scripts/migration-preflight.mjs"], {
cwd: process.cwd(),
env: { ...process.env, DATABASE_URL: absoluteDatabaseUrl(database) },
encoding: "utf8",
});
expect(preflight.status).toBe(2);
expect(preflight.stdout).toContain('"classification": "CONFLICT"');
const check = new Database(database.databasePath, { readonly: true });
try {
const columns = check.pragma("table_info(MaterialGroup)") as Array<{
name: string;
}>;
expect(columns.map((column) => column.name)).toEqual(["id"]);
} finally {
check.close();
}
}, 60_000);
});

View file

@ -0,0 +1,15 @@
import {
applyCommittedMigrations,
createDisposableDatabase,
disposeDisposableDatabase,
} from "../helpers/testDatabase";
export default function globalSetup() {
const database = createDisposableDatabase();
process.env.DATABASE_URL = database.databaseUrl;
applyCommittedMigrations(database);
return () => {
disposeDisposableDatabase(database);
};
}