import crypto from 'node:crypto'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { DatabaseSync } from 'node:sqlite'; import { describe, expect, it } from 'vitest'; import { DB, migrate } from '../server/db.ts'; import { MIGRATIONS } from '../server/migrations.ts'; import { importV1 } from '../server/services/v1import.ts'; import { createTestApp } from './helpers.ts'; describe('safe migration paths', () => { it('previews and imports a V1 database without changing its bytes, preserving answers and schedules', async () => { const app = await createTestApp(); const file = path.join(app.dir, 'v1-fixture.db'); const old = new DatabaseSync(file); old.exec(` CREATE TABLE Class (id TEXT, name TEXT, sortOrder INTEGER, createdAt INTEGER); CREATE TABLE MaterialGroup (id TEXT, classId TEXT, name TEXT, sortOrder INTEGER, createdAt INTEGER); CREATE TABLE Deck (id TEXT, classId TEXT, groupId TEXT, name TEXT, description TEXT, sortOrder INTEGER, createdAt INTEGER); CREATE TABLE Flashcard (id TEXT, deckId TEXT, front TEXT, back TEXT, sortOrder INTEGER); CREATE TABLE QuizSet (id TEXT, classId TEXT, groupId TEXT, name TEXT, description TEXT, sortOrder INTEGER, createdAt INTEGER); CREATE TABLE Question (id TEXT, quizSetId TEXT, type TEXT, prompt TEXT, rationale TEXT, category TEXT, sortOrder INTEGER); CREATE TABLE AnswerOption (id TEXT, questionId TEXT, text TEXT, isCorrect INTEGER, sortOrder INTEGER); CREATE TABLE QuizAttempt (id TEXT, quizSetId TEXT, score REAL, maxScore INTEGER, answersJson TEXT, isPartialRetake INTEGER, completedAt INTEGER); CREATE TABLE SpacedRepetitionCardState (flashcardId TEXT, state INTEGER, reps INTEGER, due INTEGER, stability REAL, difficulty REAL, scheduledDays INTEGER, learningSteps INTEGER, lapses INTEGER, lastReview INTEGER, firstReviewedAt INTEGER); INSERT INTO Class VALUES ('c','Legacy class',0,1700000000000); INSERT INTO MaterialGroup VALUES ('g','c','Legacy group',0,1700000000000); INSERT INTO Deck VALUES ('d','c','g','Legacy deck','',0,1700000000000); INSERT INTO Flashcard VALUES ('f','d','Term','Definition',0); INSERT INTO QuizSet VALUES ('z','c','g','Legacy quiz','',0,1700000000000); INSERT INTO Question VALUES ('q','z','MULTIPLE_CHOICE','Pick A','Reason','Topic',0); INSERT INTO AnswerOption VALUES ('a','q','A',1,0),('b','q','B',0,1); INSERT INTO QuizAttempt VALUES ('attempt','z',1,1,'{"q":["a"]}',0,1700000000000); INSERT INTO SpacedRepetitionCardState VALUES ('f',2,7,1800000000000,15,5,14,0,1,1700000000000,1600000000000); `); old.close(); const digest = () => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex'); const before = digest(); try { expect(importV1(app.ctx, file, { dryRun: true })).toMatchObject({ classes: 1, quizzes: 1, cards: 1, attempts: 1 }); expect(app.ctx.db.get<{ n: number }>('SELECT count(*) AS n FROM classes')?.n).toBe(0); importV1(app.ctx, file); expect(digest()).toBe(before); const classes = (await app.api('GET', '/api/classes')).body.classes; expect(classes[0].name).toBe('Legacy class'); const card = app.ctx.db.get<{ reps: number; due: number }>('SELECT reps, due FROM cards'); expect(card).toMatchObject({ reps: 7, due: 1800000000000 }); const attempt = app.ctx.db.get<{ id: string }>('SELECT id FROM attempts')!; const result = (await app.api('GET', `/api/attempts/${attempt.id}`)).body; expect(JSON.stringify(result)).toContain('Pick A'); expect(app.ctx.db.get<{ score: number }>('SELECT score FROM responses')?.score).toBe(1); expect(app.ctx.db.all('PRAGMA foreign_key_check')).toEqual([]); } finally { app.close(); } }); it('backs up before a schema change and rolls back a failed migration', () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'studydesk-migration-test-')); const db = new DB(path.join(dir, 'test.db')); try { migrate(db, dir); db.run("INSERT INTO settings VALUES ('fixture', 'preserved')"); MIGRATIONS.push({ id: 999999, name: 'test_failure', sql: 'CREATE TABLE should_rollback (id INTEGER); INVALID SQL;' }); try { expect(() => migrate(db, dir)).toThrow(); expect(db.get("SELECT name FROM sqlite_master WHERE name = 'should_rollback'")).toBeUndefined(); expect(db.get<{ value: string }>("SELECT value FROM settings WHERE key = 'fixture'")?.value).toBe('preserved'); expect(fs.readdirSync(dir).some((n) => n.startsWith('pre-migration-'))).toBe(true); } finally { MIGRATIONS.pop(); } } finally { db.close(); fs.rmSync(dir, { recursive: true, force: true }); } }); });