Files
vitfit-r2/V2/app/core/db.js
T
2026-06-13 08:03:45 -04:00

92 lines
2.8 KiB
JavaScript

'use strict';
const { Sequelize, DataTypes } = require('sequelize');
const path = require('path');
const fs = require('fs');
const logger = require('./logger');
let sequelize;
let models = {};
function initDb() {
const dbPath = process.env.DB_PATH || path.join(__dirname, '..', 'database.sqlite');
sequelize = new Sequelize({
dialect: 'sqlite',
storage: dbPath,
logging: (sql) => logger.trace({ sql }, 'SQL'),
});
// Required SQLite pragmas
sequelize.query('PRAGMA journal_mode = WAL;');
sequelize.query('PRAGMA busy_timeout = 5000;');
sequelize.query('PRAGMA foreign_keys = ON;');
// Register all models by scanning module directories
const modulesDir = path.join(__dirname, '..', 'modules');
fs.readdirSync(modulesDir).forEach(name => {
const modelPath = path.join(modulesDir, name, 'model.js');
if (fs.existsSync(modelPath)) {
const moduleModels = require(modelPath)(sequelize, DataTypes);
Object.assign(models, moduleModels);
}
});
// Run associations after all models are loaded
Object.values(models).forEach(model => {
if (typeof model.associate === 'function') {
model.associate(models);
}
});
logger.info({ dbPath }, 'Database initialized');
return sequelize.authenticate();
}
async function runMigrations() {
const { Umzug, SequelizeStorage } = require('umzug');
// Collect all migration files from modules/*/migrations/
const modulesDir = path.join(__dirname, '..', 'modules');
const migrationFiles = [];
fs.readdirSync(modulesDir).sort().forEach(moduleName => {
const migrationsDir = path.join(modulesDir, moduleName, 'migrations');
if (fs.existsSync(migrationsDir)) {
fs.readdirSync(migrationsDir).sort().forEach(file => {
if (file.endsWith('.js')) {
migrationFiles.push(path.join(migrationsDir, file));
}
});
}
});
// Sort globally by filename prefix (001, 002, ...)
migrationFiles.sort((a, b) => path.basename(a).localeCompare(path.basename(b)));
const umzug = new Umzug({
migrations: migrationFiles.map(filePath => ({
name: path.basename(filePath, '.js'),
path: filePath,
up: async ({ context }) => require(filePath).up(context, Sequelize),
down: async ({ context }) => require(filePath).down(context, Sequelize),
})),
context: sequelize.getQueryInterface(),
storage: new SequelizeStorage({ sequelize }),
logger,
});
const pending = await umzug.pending();
if (pending.length > 0) {
logger.info({ count: pending.length }, 'Running pending migrations');
await umzug.up();
logger.info('Migrations complete');
}
}
function getSequelize() {
return sequelize;
}
module.exports = { initDb, runMigrations, getSequelize, get sequelize() { return sequelize; }, get models() { return models; } };