fix(db): clear prepared statements on backup restore

This commit is contained in:
nyatoru
2026-02-24 00:35:29 +07:00
parent 238e080928
commit ac3d251a1a
3 changed files with 31 additions and 0 deletions

View File

@@ -350,6 +350,22 @@ export async function isModelAllowedForKey(key, modelId) {
return allowed;
}
/**
* Clear prepared statements cache (called on database reset/restore)
* Prepared statements are bound to a specific database connection,
* so they must be cleared when the connection is reset.
*/
function clearPreparedStatementCache() {
_stmtGetAllKeys = null;
_stmtGetKeyById = null;
_stmtValidateKey = null;
_stmtGetKeyMetadata = null;
_stmtInsertKey = null;
_stmtUpdatePermissions = null;
_stmtDeleteKey = null;
_schemaChecked = false; // Also reset schema check for new connection
}
/**
* Clear all caches (exported for testing/debugging)
*/
@@ -358,3 +374,12 @@ export function clearApiKeyCaches() {
_modelPermissionCache.clear();
_regexCache.clear();
}
/**
* Reset all cached state for database connection reset/restore.
* Called by backup.ts when the database is restored.
*/
export function resetApiKeyState() {
clearPreparedStatementCache();
clearApiKeyCaches();
}

View File

@@ -14,6 +14,7 @@ import {
DB_BACKUPS_DIR,
DATA_DIR,
} from "./core";
import { resetApiKeyState } from "./apiKeys";
// ──────────────── Backup Config ────────────────
@@ -181,6 +182,9 @@ export async function restoreDbBackup(backupId) {
// Close and reset current connection
resetDbInstance();
// Clear all cached prepared statements and other state bound to the old connection
resetApiKeyState();
// Remove main file and WAL sidecars to avoid stale frame replay after restore.
const sqliteFilesToReplace = [
SQLITE_FILE,

View File

@@ -62,6 +62,8 @@ export {
getApiKeyMetadata,
updateApiKeyPermissions,
isModelAllowedForKey,
clearApiKeyCaches,
resetApiKeyState,
} from "./db/apiKeys";
export {