From 26747f4d8b7901e3be4621908b3acebafa048a2f Mon Sep 17 00:00:00 2001 From: tyuXX Date: Thu, 12 Nov 2026 08:44:58 +0000 Subject: [PATCH] fix: support built-in node:sqlite on Node 26 LTS to resolve native bindings failure --- package.json | 7 +- src/services/db.ts | 8 +- src/services/session-store.ts | 6 +- src/services/sqlite-driver.ts | 254 ++++++++++++++++++++++++++++++++++ test/run-tests.ts | 99 +++++++++++++ 5 files changed, 365 insertions(+), 9 deletions(-) create mode 100644 src/services/sqlite-driver.ts diff --git a/package.json b/package.json index 6a02db0..89b60f1 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,8 @@ "copy-assets": "node -e \"const fs=require('fs'); fs.cpSync('views', 'dist/views', {recursive: true}); fs.cpSync('public', 'dist/public', {recursive: true});\"", "start": "node dist/server.js", "dev": "ts-node-dev --respawn --transpile-only src/server.ts", - "test": "ts-node test/run-tests.ts" + "test": "ts-node test/run-tests.ts", + "rebuild": "npm rebuild better-sqlite3 --build-from-source" }, "keywords": [ "bekultur", @@ -20,7 +21,6 @@ "license": "ISC", "dependencies": { "axios": "^1.7.7", - "better-sqlite3": "^11.10.0", "cheerio": "^1.0.0-rc.12", "cookie-parser": "^1.4.7", "dotenv": "^16.4.5", @@ -30,6 +30,9 @@ "express-session": "^1.18.1", "helmet": "^8.3.0" }, + "optionalDependencies": { + "better-sqlite3": "^11.10.0" + }, "devDependencies": { "@resvg/resvg-js": "^2.6.2", "@types/better-sqlite3": "^9.6.0", diff --git a/src/services/db.ts b/src/services/db.ts index db74ba2..7ffe966 100644 --- a/src/services/db.ts +++ b/src/services/db.ts @@ -2,7 +2,7 @@ import '../utils/time'; import { toIstanbulIsoString } from '../utils/time'; import fs from 'fs'; import path from 'path'; -import Database from 'better-sqlite3'; +import { openDatabase, SQLiteDatabase } from './sqlite-driver'; import { StudentStore, Assignment, @@ -56,7 +56,7 @@ interface AssignmentRow { export class LocalDatabase { private static instance: LocalDatabase | null = null; - private sqlite: Database.Database; + private sqlite: SQLiteDatabase; private dbPath: string; public constructor(customDbPath?: string) { @@ -67,7 +67,7 @@ export class LocalDatabase { fs.mkdirSync(dir, { recursive: true }); } - this.sqlite = new Database(this.dbPath); + this.sqlite = openDatabase(this.dbPath); this.initSchema(); this.syncPersistentSecrets(); this.sanitizeStoredCredentials(); @@ -140,7 +140,7 @@ export class LocalDatabase { } } - public getSqliteDb(): Database.Database { + public getSqliteDb(): SQLiteDatabase { return this.sqlite; } diff --git a/src/services/session-store.ts b/src/services/session-store.ts index ede088f..9127bc3 100644 --- a/src/services/session-store.ts +++ b/src/services/session-store.ts @@ -1,18 +1,18 @@ import session from 'express-session'; -import Database from 'better-sqlite3'; +import { SQLiteDatabase } from './sqlite-driver'; import { encryptCredential, decryptCredential } from './secrets'; const DEFAULT_TTL_MS = 14 * 24 * 60 * 60 * 1000; // 14 days const DEFAULT_PRUNE_INTERVAL_MS = 15 * 60 * 1000; // 15 minutes export interface SQLiteSessionStoreOptions { - db: Database.Database; + db: SQLiteDatabase; ttlMs?: number; pruneIntervalMs?: number; } export class SQLiteSessionStore extends session.Store { - private db: Database.Database; + private db: SQLiteDatabase; private ttlMs: number; private pruneTimer: NodeJS.Timeout | null = null; diff --git a/src/services/sqlite-driver.ts b/src/services/sqlite-driver.ts new file mode 100644 index 0000000..1d476f3 --- /dev/null +++ b/src/services/sqlite-driver.ts @@ -0,0 +1,254 @@ +import fs from 'fs'; +import path from 'path'; + +export interface SQLiteRunResult { + changes: number; + lastInsertRowid: number | bigint; +} + +export interface SQLiteStatement { + run(...params: any[]): SQLiteRunResult; + get(...params: any[]): any; + all(...params: any[]): any[]; +} + +export interface SQLiteDatabase { + prepare(sql: string): SQLiteStatement; + exec(sql: string): void; + pragma(pragmaStr: string): any; + transaction any>(fn: T): T; + close(): void; + readonly open: boolean; + readonly driver: 'node:sqlite' | 'better-sqlite3'; +} + +export class BetterSqlite3StatementWrapper implements SQLiteStatement { + constructor(private stmt: any) {} + + public run(...params: any[]): SQLiteRunResult { + if (params.length === 1 && typeof params[0] === 'object' && params[0] !== null && !Array.isArray(params[0])) { + const res = this.stmt.run(params[0]); + return { + changes: Number(res?.changes) || 0, + lastInsertRowid: res?.lastInsertRowid ?? 0 + }; + } + const res = this.stmt.run(...params); + return { + changes: Number(res?.changes) || 0, + lastInsertRowid: res?.lastInsertRowid ?? 0 + }; + } + + public get(...params: any[]): any { + if (params.length === 1 && typeof params[0] === 'object' && params[0] !== null && !Array.isArray(params[0])) { + return this.stmt.get(params[0]); + } + return this.stmt.get(...params); + } + + public all(...params: any[]): any[] { + if (params.length === 1 && typeof params[0] === 'object' && params[0] !== null && !Array.isArray(params[0])) { + return this.stmt.all(params[0]); + } + return this.stmt.all(...params); + } +} + +export class BetterSqlite3DatabaseWrapper implements SQLiteDatabase { + public readonly driver = 'better-sqlite3'; + + constructor(private rawDb: any) {} + + public prepare(sql: string): SQLiteStatement { + return new BetterSqlite3StatementWrapper(this.rawDb.prepare(sql)); + } + + public exec(sql: string): void { + this.rawDb.exec(sql); + } + + public pragma(pragmaStr: string): any { + return this.rawDb.pragma(pragmaStr); + } + + public transaction any>(fn: T): T { + return this.rawDb.transaction(fn); + } + + public close(): void { + this.rawDb.close(); + } + + public get open(): boolean { + return Boolean(this.rawDb.open); + } +} + +export class NodeSqliteStatementWrapper implements SQLiteStatement { + private stmt: any; + private namedParamKeys: string[] | null = null; + + constructor(stmt: any, sql: string) { + this.stmt = stmt; + const matches = sql.match(/[@:$]([a-zA-Z0-9_]+)/g); + if (matches && matches.length > 0) { + this.namedParamKeys = Array.from(new Set(matches.map(m => m.slice(1)))); + } + } + + private sanitizeArgs(params: any[]): any[] { + if (params.length === 1 && typeof params[0] === 'object' && params[0] !== null && !Array.isArray(params[0])) { + const obj = params[0]; + if (this.namedParamKeys && this.namedParamKeys.length > 0) { + const filtered: Record = {}; + for (const key of this.namedParamKeys) { + const val = + obj[key] !== undefined + ? obj[key] + : obj[`@${key}`] !== undefined + ? obj[`@${key}`] + : obj[`:${key}`] !== undefined + ? obj[`:${key}`] + : obj[`$${key}`] !== undefined + ? obj[`$${key}`] + : null; + filtered[key] = val === undefined ? null : val; + } + return [filtered]; + } + return [obj]; + } + return params.map(p => (p === undefined ? null : p)); + } + + public run(...params: any[]): SQLiteRunResult { + const cleanParams = this.sanitizeArgs(params); + const res = this.stmt.run(...cleanParams); + return { + changes: typeof res?.changes === 'number' ? res.changes : (Number(res?.changes) || 0), + lastInsertRowid: res?.lastInsertRowid ?? 0 + }; + } + + public get(...params: any[]): any { + const cleanParams = this.sanitizeArgs(params); + return this.stmt.get(...cleanParams); + } + + public all(...params: any[]): any[] { + const cleanParams = this.sanitizeArgs(params); + return this.stmt.all(...cleanParams); + } +} + +export class NodeSqliteDatabaseWrapper implements SQLiteDatabase { + public readonly driver = 'node:sqlite'; + private _isOpen = true; + + constructor(private rawDb: any) {} + + public prepare(sql: string): SQLiteStatement { + const rawStmt = this.rawDb.prepare(sql); + return new NodeSqliteStatementWrapper(rawStmt, sql); + } + + public exec(sql: string): void { + this.rawDb.exec(sql); + } + + public pragma(pragmaStr: string): any { + const trimmed = pragmaStr.trim(); + const cleanPragma = trimmed.replace(/^PRAGMA\s+/i, ''); + if (cleanPragma.toLowerCase().startsWith('table_info') || !cleanPragma.includes('=')) { + try { + return this.prepare(`PRAGMA ${cleanPragma}`).all(); + } catch { + try { + return this.prepare(`PRAGMA ${cleanPragma}`).get(); + } catch { + this.exec(`PRAGMA ${cleanPragma}`); + return []; + } + } + } else { + this.exec(`PRAGMA ${cleanPragma}`); + return []; + } + } + + public transaction any>(fn: T): T { + const wrapped = ((...args: any[]) => { + this.exec('BEGIN IMMEDIATE'); + try { + const result = fn(...args); + this.exec('COMMIT'); + return result; + } catch (err) { + try { + this.exec('ROLLBACK'); + } catch { + // ignore rollback errors if database already rolled back + } + throw err; + } + }) as T; + return wrapped; + } + + public close(): void { + if (this._isOpen) { + try { + this.rawDb.close(); + } finally { + this._isOpen = false; + } + } + } + + public get open(): boolean { + return this._isOpen; + } +} + +/** + * Open a SQLite database instance. + * Automatically selects built-in 'node:sqlite' on Node >= 22.5.0 (which resolves missing + * native addon bindings on newer Node runtimes like Node 26 LTS), or falls back to 'better-sqlite3' + * on older Node versions (< 22) such as Docker Alpine builds. + */ +export function openDatabase(dbPath: string): SQLiteDatabase { + const dir = path.dirname(dbPath); + if (dir && dir !== '.' && !fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + + // 1. Try built-in node:sqlite (Node >= 22.5.0, including Node 26 LTS) + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const nodeSqlite = require('node:sqlite'); + const DatabaseClass = nodeSqlite.DatabaseSync || nodeSqlite.Database; + if (typeof DatabaseClass === 'function') { + const db = new DatabaseClass(dbPath); + return new NodeSqliteDatabaseWrapper(db); + } + } catch { + // node:sqlite not supported on this Node version (< 22) + } + + // 2. Fallback to better-sqlite3 (Node 18 / 20 or when node:sqlite is absent) + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const BetterSqlite3 = require('better-sqlite3'); + const db = new BetterSqlite3(dbPath); + return new BetterSqlite3DatabaseWrapper(db); + } catch (betterSqliteErr: any) { + throw new Error( + `Failed to initialize SQLite database at '${dbPath}'. ` + + `Neither built-in 'node:sqlite' nor 'better-sqlite3' could be loaded.\n` + + `- error: ${betterSqliteErr?.message || betterSqliteErr}\n` + + `Fix for Node.js < 22: Run 'npm rebuild better-sqlite3 --build-from-source'\n` + + `Fix for Node.js >= 22: Ensure Node's built-in 'node:sqlite' module is accessible.` + ); + } +} diff --git a/test/run-tests.ts b/test/run-tests.ts index f486836..9e281a6 100644 --- a/test/run-tests.ts +++ b/test/run-tests.ts @@ -19,6 +19,12 @@ import { getIstanbulMondayStart, isBeforeCurrentMondayInIstanbul } from '../src/utils/time'; +import { + openDatabase, + NodeSqliteDatabaseWrapper, + NodeSqliteStatementWrapper, + BetterSqlite3DatabaseWrapper +} from '../src/services/sqlite-driver'; import { Assignment, Lesson, ExamReportDetail } from '../src/types'; // Configure isolated temporary directory BEFORE any server/db singleton initialization @@ -1220,6 +1226,99 @@ async function runAllTests() { } }); + await test('SQLite Driver & Runtime Compatibility: seamlessly abstracts node:sqlite and better-sqlite3 with parameter sanitization, transactions, and pragmas', async () => { + // 1. Test active database driver returned by openDatabase + const activeDb = openDatabase(path.join(tempDir, 'active-driver.db')); + assert.strictEqual(activeDb.open, true, 'Active driver must report open = true'); + activeDb.exec('CREATE TABLE test_tbl (id TEXT PRIMARY KEY, val TEXT);'); + activeDb.prepare('INSERT INTO test_tbl (id, val) VALUES (?, ?)').run('id1', 'val1'); + const row = activeDb.prepare('SELECT val FROM test_tbl WHERE id = ?').get('id1'); + assert.strictEqual(row?.val, 'val1'); + activeDb.close(); + assert.strictEqual(activeDb.open, false, 'Database must report open = false after close'); + + // 2. Test NodeSqliteDatabaseWrapper simulation to verify full parity on Node >= 22 (node:sqlite) + const mockSqliteCalls: { exec: string[]; prepared: string[]; closed: boolean } = { + exec: [], + prepared: [], + closed: false + }; + + const mockRawDb = { + exec(sql: string) { + mockSqliteCalls.exec.push(sql); + }, + prepare(sql: string) { + mockSqliteCalls.prepared.push(sql); + return { + run(...args: any[]) { + return { changes: 1, lastInsertRowid: 42 }; + }, + get(...args: any[]) { + return { query: sql, args }; + }, + all(...args: any[]) { + if (sql.includes('table_info')) { + return [{ cid: 0, name: 'last_login_at', type: 'TEXT' }]; + } + return [{ query: sql, args }]; + } + }; + }, + close() { + mockSqliteCalls.closed = true; + } + }; + + const nodeWrapper = new NodeSqliteDatabaseWrapper(mockRawDb); + assert.strictEqual(nodeWrapper.driver, 'node:sqlite'); + assert.strictEqual(nodeWrapper.open, true); + + // Verify pragma query vs command execution + const pragmaCols = nodeWrapper.pragma('table_info(students)'); + assert.deepStrictEqual(pragmaCols, [{ cid: 0, name: 'last_login_at', type: 'TEXT' }]); + + nodeWrapper.pragma('journal_mode = WAL'); + assert(mockSqliteCalls.exec.includes('PRAGMA journal_mode = WAL'), 'Pragma commands must run via exec'); + + // Verify named parameter mapping and sanitization for upserts + const namedStmt = nodeWrapper.prepare('INSERT INTO assignments (id, student_id) VALUES (@id, @student_id)'); + const runRes = namedStmt.run({ + id: 'hw_1', + student_id: 'std_99', + extra_unrelated_field: 'should_be_stripped_for_node_sqlite' + }); + assert.strictEqual(runRes.changes, 1); + assert.strictEqual(runRes.lastInsertRowid, 42); + + // Verify positional parameter sanitization (converting undefined to null) + const posStmt = nodeWrapper.prepare('SELECT * FROM students WHERE student_id = ? AND last_synced = ?'); + const getRes = posStmt.get('std_1', undefined); + assert.deepStrictEqual(getRes.args, ['std_1', null], 'Undefined positional arguments must be converted to null'); + + // Verify transaction behavior + let txExecuted = false; + const tx = nodeWrapper.transaction(() => { + txExecuted = true; + }); + tx(); + assert.strictEqual(txExecuted, true); + assert(mockSqliteCalls.exec.includes('BEGIN IMMEDIATE')); + assert(mockSqliteCalls.exec.includes('COMMIT')); + + // Verify transaction rollback on error + const failingTx = nodeWrapper.transaction(() => { + throw new Error('Database transaction abort test'); + }); + assert.throws(() => failingTx(), /Database transaction abort test/); + assert(mockSqliteCalls.exec.includes('ROLLBACK')); + + // Verify close + nodeWrapper.close(); + assert.strictEqual(nodeWrapper.open, false); + assert.strictEqual(mockSqliteCalls.closed, true); + }); + // Optional Live Portal Test (via environment variables only) const testStudentId = process.env.TEST_STUDENT_ID; const testPassword = process.env.TEST_PASSWORD;