35 lines
1.5 KiB
TypeScript
35 lines
1.5 KiB
TypeScript
import { DatabaseSync } from 'node:sqlite'
|
|
import { mkdirSync } from 'node:fs'
|
|
import { dirname, join } from 'node:path'
|
|
import { fileURLToPath } from 'node:url'
|
|
import { TABLE_DEFINITIONS } from './db/tableRegistry'
|
|
|
|
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
const dbPath = join(__dirname, 'data', 'assignment-monitor.sqlite3')
|
|
mkdirSync(dirname(dbPath), { recursive: true })
|
|
|
|
export const db = new DatabaseSync(dbPath)
|
|
|
|
/**
|
|
* `CREATE TABLE IF NOT EXISTS` legt eine fehlende Tabelle vollständig an, migriert aber niemals eine
|
|
* bereits bestehende — neue Spalten, die tableRegistry.ts für eine vorhandene Tabelle ergänzt (z.B.
|
|
* suggestedAchievements auf feedbackDimensionTexts, 2026-07-07), fehlen dort sonst dauerhaft und
|
|
* führen erst zur Laufzeit zu "no column named ..."-Fehlern. Deshalb zusätzlich per PRAGMA table_info
|
|
* abgleichen und fehlende Spalten per ALTER TABLE nachziehen.
|
|
*/
|
|
for (const table of TABLE_DEFINITIONS) {
|
|
const columnsSql = table.columns.map(c => `"${c.name}" ${c.sqlType}`).join(', ')
|
|
db.exec(`CREATE TABLE IF NOT EXISTS "${table.name}" (id INTEGER PRIMARY KEY AUTOINCREMENT, ${columnsSql})`)
|
|
|
|
const existingColumns = new Set(
|
|
(db.prepare(`PRAGMA table_info("${table.name}")`).all() as { name: string }[]).map(c => c.name),
|
|
)
|
|
for (const col of table.columns) {
|
|
if (!existingColumns.has(col.name)) {
|
|
db.exec(`ALTER TABLE "${table.name}" ADD COLUMN "${col.name}" ${col.sqlType}`)
|
|
}
|
|
}
|
|
}
|
|
|
|
console.log(`[db] SQLite bereit unter ${dbPath}`)
|