22c7b38e9a
Добавлено такое же действие, как [Z] в control-panel: POST /api/admin/reset-system (+ /reset-system/plan для предпросмотра), только admin. Общая логика вынесена в src/services/systemReset.js (classify/pickKeptAdmin/runReset) — реюзится CLI и эндпоинтом. Веб-эндпоинт безопаснее CLI: сохраняет ТЕКУЩЕГО админа (оператор остаётся залогинен), делает бэкап БД ДО сброса (wal_checkpoint + копия в data/backups/), требует body.confirm='СБРОС'. UI — «Опасная зона» в overview-секции: предпросмотр плана + ввод «СБРОС» + результат с именем бэкапа. db.js: добавлен db._path (нужен бэкапу при сбросе). Логика проверена смоуком на копии живой БД (16 юзеров удалено, контент сохранён, REASSIGN на админа, гейм-счётчики обнулены, 0 висячих FK). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
53 lines
2.0 KiB
JavaScript
53 lines
2.0 KiB
JavaScript
const { DatabaseSync } = require('node:sqlite');
|
|
const path = require('path');
|
|
|
|
const fs = require('fs');
|
|
// Resolve DB_PATH: if absolute — use as-is; if relative — resolve from backend/ dir;
|
|
// fallback to __dirname-relative default so CWD never matters.
|
|
const _rawPath = process.env.DB_PATH;
|
|
const _backendDir = path.join(__dirname, '../../');
|
|
const dbPath = _rawPath
|
|
? (path.isAbsolute(_rawPath) ? _rawPath : path.resolve(_backendDir, _rawPath))
|
|
: path.join(__dirname, '../../data/learnspace.db');
|
|
const dbDir = path.dirname(dbPath);
|
|
if (!fs.existsSync(dbDir)) fs.mkdirSync(dbDir, { recursive: true });
|
|
|
|
// Auto-migrate from old location (backend/learnspace.db → backend/data/learnspace.db)
|
|
const oldPath = path.join(__dirname, '../../learnspace.db');
|
|
if (!fs.existsSync(dbPath) && fs.existsSync(oldPath)) {
|
|
fs.copyFileSync(oldPath, dbPath);
|
|
// Also copy WAL/SHM if present
|
|
if (fs.existsSync(oldPath + '-wal')) fs.copyFileSync(oldPath + '-wal', dbPath + '-wal');
|
|
if (fs.existsSync(oldPath + '-shm')) fs.copyFileSync(oldPath + '-shm', dbPath + '-shm');
|
|
console.log('[db] Migrated database from', oldPath, '→', dbPath);
|
|
}
|
|
|
|
const db = new DatabaseSync(dbPath);
|
|
|
|
db.exec('PRAGMA journal_mode = WAL');
|
|
db.exec('PRAGMA synchronous = NORMAL'); // safe with WAL, ~5x faster than FULL
|
|
db.exec('PRAGMA foreign_keys = ON');
|
|
db.exec('PRAGMA cache_size = -16000'); // 16 MB page cache (was default ~2 MB)
|
|
db.exec('PRAGMA temp_store = MEMORY'); // temp tables in RAM, not disk
|
|
|
|
/**
|
|
* Run a synchronous function inside a BEGIN/COMMIT/ROLLBACK transaction.
|
|
* Returns the value returned by fn(), or rethrows on error.
|
|
*/
|
|
db.transaction = function transaction(fn) {
|
|
return (...args) => {
|
|
db.exec('BEGIN');
|
|
try {
|
|
const result = fn(...args);
|
|
db.exec('COMMIT');
|
|
return result;
|
|
} catch (err) {
|
|
db.exec('ROLLBACK');
|
|
throw err;
|
|
}
|
|
};
|
|
};
|
|
|
|
db._path = dbPath; // абсолютный путь к файлу БД (нужен бэкапу при сбросе системы)
|
|
module.exports = db;
|