Start Study Desk V2: remove V1 sources, add backend foundation

V1 remains intact on main and in history. This branch replaces it with a new
application: node:sqlite storage with migrations, scrypt auth and sessions,
content/SRS/attempt/stats services, document extraction and chunking, a
provider-neutral AI layer (OpenAI, Anthropic, Gemini, OpenAI-compatible,
Ollama), the generation pipeline and the tool-using assistant.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-11 08:16:41 -07:00
parent 7bd0a9aad4
commit 3e74ecd843
268 changed files with 17740 additions and 55423 deletions

View file

@ -1,98 +0,0 @@
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 REMOVAL_MIGRATION = "20260808100000_remove_arcade";
const databases: DisposableDatabase[] = [];
afterEach(() => {
for (const database of databases.splice(0)) {
disposeDisposableDatabase(database);
}
});
describe("Arcade removal migration", () => {
it("removes Arcade data while preserving the rest of the study database", () => {
const database = createDisposableDatabase();
databases.push(database);
applyCommittedMigrations(database, { through: "20260807092000_add_progress_revisions" });
const sqlite = new Database(database.databasePath);
try {
sqlite.pragma("foreign_keys = ON");
sqlite.exec(`
INSERT INTO "Class" ("id", "slug", "name")
VALUES ('class-arcade-removal', 'arcade-removal', 'Preserved class');
INSERT INTO "MaterialGroup" ("id", "classId", "name", "type") VALUES
('group-deck-arcade-removal', 'class-arcade-removal', 'Preserved deck group', 'DECK'),
('group-quiz-arcade-removal', 'class-arcade-removal', 'Preserved quiz group', 'QUIZ');
INSERT INTO "Deck" ("id", "classId", "groupId", "name")
VALUES ('deck-arcade-removal', 'class-arcade-removal', 'group-deck-arcade-removal', 'Preserved deck');
INSERT INTO "Flashcard" ("id", "deckId", "front", "back")
VALUES ('card-arcade-removal', 'deck-arcade-removal', 'Preserved front', 'Preserved back');
INSERT INTO "QuizSet" ("id", "classId", "groupId", "name")
VALUES ('quiz-arcade-removal', 'class-arcade-removal', 'group-quiz-arcade-removal', 'Preserved quiz');
INSERT INTO "Question" ("id", "quizSetId", "type", "prompt", "rationale", "category")
VALUES ('question-arcade-removal', 'quiz-arcade-removal', 'MULTIPLE_CHOICE', 'Preserved prompt', 'Preserved rationale', 'Preserved category');
INSERT INTO "AnswerOption" ("id", "questionId", "text", "isCorrect")
VALUES ('option-arcade-removal', 'question-arcade-removal', 'Preserved option', 1);
INSERT INTO "StudyProgress" ("id", "contentType", "deckId", "mode", "orderJson", "updatedAt", "sessionId", "revision") VALUES
('deck-progress-arcade-removal', 'DECK', 'deck-arcade-removal', 'SEQUENTIAL', '["card-arcade-removal"]', CURRENT_TIMESTAMP, 'session-deck', 2),
('quiz-progress-arcade-removal', 'QUIZ', NULL, 'SEQUENTIAL', '["question-arcade-removal"]', CURRENT_TIMESTAMP, 'session-quiz', 3);
UPDATE "StudyProgress"
SET "quizSetId" = 'quiz-arcade-removal'
WHERE "id" = 'quiz-progress-arcade-removal';
INSERT INTO "ShareLink" ("id", "targetType", "groupId")
VALUES ('share-arcade-removal', 'GROUP', 'group-quiz-arcade-removal');
INSERT INTO "Setting" ("key", "value") VALUES
('llmInstructionsFlashcards', 'keep this'),
('llmInstructionsConnections', 'remove this'),
('llmInstructionsCrossword', 'remove this');
INSERT INTO "StudyActivity" ("id", "type") VALUES
('activity-flashcard', 'FLASHCARD'),
('activity-question', 'QUIZ_QUESTION'),
('activity-group', 'ARCADE_GROUP'),
('activity-word', 'ARCADE_WORD');
INSERT INTO "ArcadePack"
("id", "classId", "gameType", "name", "schemaVersion", "sourceJson", "normalizedJson", "validationReportJson", "updatedAt")
VALUES ('arcade-pack', 'class-arcade-removal', 'connections', 'Removed pack', 1, '{}', '{}', '{}', CURRENT_TIMESTAMP);
INSERT INTO "ArcadeAttempt"
("id", "arcadePackId", "mode", "score", "maxScore", "accuracy", "durationSeconds", "mistakes", "hintsUsed", "settingsJson", "resultsJson", "seed")
VALUES ('arcade-attempt', 'arcade-pack', 'CLASSIC', 0, 400, 0, 0, 0, 0, '{}', '{}', 'seed');
`);
sqlite.exec(readFileSync(
path.join(process.cwd(), "prisma", "migrations", REMOVAL_MIGRATION, "migration.sql"),
"utf8"
));
expect(sqlite.prepare('SELECT "name" FROM "Class" WHERE "id" = ?').get("class-arcade-removal")).toEqual({ name: "Preserved class" });
expect(sqlite.prepare('SELECT "name" FROM "Deck" WHERE "id" = ?').get("deck-arcade-removal")).toEqual({ name: "Preserved deck" });
expect(sqlite.prepare('SELECT "name" FROM "MaterialGroup" WHERE "id" = ?').get("group-deck-arcade-removal")).toEqual({ name: "Preserved deck group" });
expect(sqlite.prepare('SELECT "name" FROM "QuizSet" WHERE "id" = ?').get("quiz-arcade-removal")).toEqual({ name: "Preserved quiz" });
expect(sqlite.prepare('SELECT "text" FROM "AnswerOption" WHERE "id" = ?').get("option-arcade-removal")).toEqual({ text: "Preserved option" });
expect(sqlite.prepare('SELECT COUNT(*) AS count FROM "StudyProgress"').get()).toEqual({ count: 2 });
expect(sqlite.prepare('SELECT "targetType" FROM "ShareLink" WHERE "id" = ?').get("share-arcade-removal")).toEqual({ targetType: "GROUP" });
expect(sqlite.prepare('SELECT "key" FROM "Setting" ORDER BY "key"').all()).toEqual([
{ key: "llmInstructionsFlashcards" },
]);
expect(sqlite.prepare('SELECT "type" FROM "StudyActivity" ORDER BY "type"').all()).toEqual([
{ type: "FLASHCARD" },
{ type: "QUIZ_QUESTION" },
]);
expect(sqlite.prepare('SELECT 1 FROM sqlite_master WHERE type = ? AND name = ?').get("table", "ArcadePack")).toBeUndefined();
expect(sqlite.prepare('SELECT 1 FROM sqlite_master WHERE type = ? AND name = ?').get("table", "ArcadeAttempt")).toBeUndefined();
expect(sqlite.pragma("foreign_key_check")).toEqual([]);
expect(sqlite.pragma("integrity_check", { simple: true })).toBe("ok");
} finally {
sqlite.close();
}
});
});

View file

@ -1,41 +0,0 @@
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

@ -1,107 +0,0 @@
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

@ -1,272 +0,0 @@
import { spawnSync } from "node:child_process";
import { copyFileSync, 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, args: string[] = []) {
const result = spawnSync(
process.execPath,
[path.join(process.cwd(), "scripts", "migration-preflight.mjs"), ...args],
{
cwd: process.cwd(),
env: { ...process.env, DATABASE_URL: database.databaseUrl },
encoding: "utf8",
}
);
return { status: result.status, output: JSON.parse(result.stdout) };
}
function migrationSql(migrationName: string) {
return readFileSync(
path.join(
process.cwd(),
"prisma",
"migrations",
migrationName,
"migration.sql"
),
"utf8"
);
}
describe("material group migration preflight", () => {
it("allows startup when a fresh database does not exist yet", () => {
const database = createDisposableDatabase();
databases.push(database);
expect(inspect(database, ["--startup"])).toMatchObject({
status: 0,
output: { classification: "EMPTY", migrationsToAdopt: [] },
});
});
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("blocks startup and explicitly adopts a fully schema-pushed database after P3018", () => {
const database = create({ excludeGroup: true });
const missingMigrations = [
GROUP_MIGRATION,
"20260807091000_add_quiz_attempt_snapshot",
"20260807092000_add_progress_revisions",
];
const client = new Database(database.databasePath);
try {
for (const migrationName of missingMigrations) {
client.exec(migrationSql(migrationName));
}
client.prepare(`
INSERT INTO "_prisma_migrations"
("id", "checksum", "finished_at", "migration_name", "logs", "applied_steps_count")
VALUES (?, ?, NULL, ?, ?, 0)
`).run("failed-group-migration", "failed", GROUP_MIGRATION, "P3018");
} finally {
client.close();
}
const startup = inspect(database, ["--startup"]);
expect(startup).toMatchObject({
status: 3,
output: {
classification: "ADOPT",
migrationsToAdopt: missingMigrations,
},
});
const backupPath = path.join(database.directory, "adoption-backup.test.db");
copyFileSync(database.databasePath, backupPath);
const resolve = spawnSync(
process.execPath,
[
path.join(process.cwd(), "scripts", "migration-preflight.mjs"),
"--resolve",
"--backup",
backupPath,
],
{
cwd: process.cwd(),
env: { ...process.env, DATABASE_URL: database.databaseUrl },
encoding: "utf8",
}
);
expect(resolve.status, resolve.stderr).toBe(0);
const deploy = spawnSync(
process.execPath,
[
path.join(process.cwd(), "node_modules", "prisma", "build", "index.js"),
"migrate",
"deploy",
],
{
cwd: process.cwd(),
env: { ...process.env, DATABASE_URL: database.databaseUrl },
encoding: "utf8",
}
);
expect(deploy.status, `${deploy.stdout}\n${deploy.stderr}`).toBe(0);
expect(inspect(database)).toMatchObject({
status: 0,
output: { classification: "CURRENT", migrationsToAdopt: [] },
});
}, 30_000);
it("can resume exact adoption after some missing migrations were recorded", () => {
const database = create({ excludeGroup: true });
const client = new Database(database.databasePath);
try {
for (const migrationName of [
GROUP_MIGRATION,
"20260807091000_add_quiz_attempt_snapshot",
"20260807092000_add_progress_revisions",
]) {
client.exec(migrationSql(migrationName));
}
client.prepare(`
INSERT INTO "_prisma_migrations"
("id", "checksum", "finished_at", "migration_name", "applied_steps_count")
VALUES (?, ?, current_timestamp, ?, 1)
`).run("adopted-group-migration", "adopted", GROUP_MIGRATION);
} finally {
client.close();
}
expect(inspect(database, ["--startup"])).toMatchObject({
status: 3,
output: {
classification: "ADOPT",
migrationsToAdopt: [
"20260807091000_add_quiz_attempt_snapshot",
"20260807092000_add_progress_revisions",
],
},
});
});
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

@ -1,40 +0,0 @@
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

@ -1,174 +0,0 @@
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

@ -1,15 +0,0 @@
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);
};
}