Files
bilin/src/main/db/migrate.ts
T
bing aac51bf183 feat: deliver P2 v0.2.0 with unified editor, search, and snapshots
Implement schema v2 migration, outline/setting/inspiration CRUD, unified TipTap editing, reference panel with mentions, FTS global search, chapter version history, writing landmarks, word frequency analysis, light theme contrast fixes, and full unit/E2E test coverage.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-06 14:13:27 +08:00

46 lines
1.4 KiB
TypeScript

import type { SqliteDb } from './types'
import schemaV1 from './schema-v1.sql?raw'
import schemaV2 from './schema-v2.sql?raw'
const CURRENT_VERSION = 2
function tryAlter(db: SqliteDb, sql: string): void {
try {
db.exec(sql)
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
if (!msg.includes('duplicate column')) throw err
}
}
function applyV2(db: SqliteDb): void {
tryAlter(db, "ALTER TABLE chapters ADD COLUMN publish_status TEXT NOT NULL DEFAULT 'draft'")
tryAlter(db, 'ALTER TABLE chapters ADD COLUMN pov_character_id TEXT DEFAULT NULL')
tryAlter(db, "ALTER TABLE chapters ADD COLUMN summary TEXT DEFAULT ''")
tryAlter(db, 'ALTER TABLE chapters ADD COLUMN story_time TEXT DEFAULT NULL')
db.exec(schemaV2)
}
export function migrate(db: SqliteDb): void {
db.exec(`CREATE TABLE IF NOT EXISTS schema_version (
version INTEGER PRIMARY KEY,
applied_at TEXT NOT NULL DEFAULT (datetime('now')),
description TEXT
)`)
const row = db.prepare('SELECT MAX(version) AS v FROM schema_version').get() as { v: number | null }
let current = row?.v ?? 0
if (current >= CURRENT_VERSION) return
if (current < 1) {
db.exec(schemaV1)
db.prepare('INSERT INTO schema_version (version, description) VALUES (?, ?)').run(1, 'initial schema')
current = 1
}
if (current < 2) {
applyV2(db)
db.prepare('INSERT INTO schema_version (version, description) VALUES (?, ?)').run(2, 'P2 schema')
}
}