47 lines
1.3 KiB
TypeScript
47 lines
1.3 KiB
TypeScript
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { pool } from './pool.js';
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = path.dirname(__filename);
|
|
|
|
const MIGRATIONS_DIR = path.resolve(__dirname, '../../../db');
|
|
|
|
export async function runMigrations(): Promise<void> {
|
|
console.log('[migrate] Запуск миграций из', MIGRATIONS_DIR);
|
|
|
|
if (!fs.existsSync(MIGRATIONS_DIR)) {
|
|
console.warn('[migrate] Папка миграций не найдена, пропускаю');
|
|
return;
|
|
}
|
|
|
|
const files = fs
|
|
.readdirSync(MIGRATIONS_DIR)
|
|
.filter((f) => f.endsWith('.sql'))
|
|
.sort();
|
|
|
|
for (const file of files) {
|
|
const fullPath = path.join(MIGRATIONS_DIR, file);
|
|
const sql = fs.readFileSync(fullPath, 'utf-8');
|
|
console.log(`[migrate] → ${file}`);
|
|
try {
|
|
await pool.query(sql);
|
|
} catch (err) {
|
|
console.error(`[migrate] Ошибка в ${file}:`, err);
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
console.log('[migrate] Все миграции применены');
|
|
}
|
|
|
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
runMigrations()
|
|
.then(() => process.exit(0))
|
|
.catch((err) => {
|
|
console.error(err);
|
|
process.exit(1);
|
|
});
|
|
}
|