fix: support built-in node:sqlite on Node 26 LTS to resolve native bindings failure
This commit is contained in:
parent
43f3891e9e
commit
26747f4d8b
5 changed files with 365 additions and 9 deletions
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
|
|
|
|||
254
src/services/sqlite-driver.ts
Normal file
254
src/services/sqlite-driver.ts
Normal file
|
|
@ -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<T extends (...args: any[]) => 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<T extends (...args: any[]) => 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<string, any> = {};
|
||||
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<T extends (...args: any[]) => 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.`
|
||||
);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue