fix: track applied migrations to prevent duplicate seeds on restart
This commit is contained in:
@@ -16,18 +16,40 @@ export async function runMigrations(): Promise<void> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Создаём таблицу учёта миграций если её нет
|
||||||
|
await pool.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS _migrations (
|
||||||
|
filename TEXT PRIMARY KEY,
|
||||||
|
applied_at TIMESTAMPTZ DEFAULT now()
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
const files = fs
|
const files = fs
|
||||||
.readdirSync(MIGRATIONS_DIR)
|
.readdirSync(MIGRATIONS_DIR)
|
||||||
.filter((f) => f.endsWith('.sql'))
|
.filter((f) => f.endsWith('.sql'))
|
||||||
.sort();
|
.sort();
|
||||||
|
|
||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
|
// Проверяем — уже применялась?
|
||||||
|
const { rowCount } = await pool.query(
|
||||||
|
'SELECT 1 FROM _migrations WHERE filename = $1',
|
||||||
|
[file]
|
||||||
|
);
|
||||||
|
if (rowCount && rowCount > 0) {
|
||||||
|
console.log(`[migrate] ✓ ${file} (уже применена)`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
const fullPath = path.join(MIGRATIONS_DIR, file);
|
const fullPath = path.join(MIGRATIONS_DIR, file);
|
||||||
const sql = fs.readFileSync(fullPath, 'utf-8');
|
const sql = fs.readFileSync(fullPath, 'utf-8');
|
||||||
console.log(`[migrate] → ${file}`);
|
console.log(`[migrate] → ${file}`);
|
||||||
try {
|
try {
|
||||||
|
await pool.query('BEGIN');
|
||||||
await pool.query(sql);
|
await pool.query(sql);
|
||||||
|
await pool.query('INSERT INTO _migrations (filename) VALUES ($1)', [file]);
|
||||||
|
await pool.query('COMMIT');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
await pool.query('ROLLBACK');
|
||||||
console.error(`[migrate] Ошибка в ${file}:`, err);
|
console.error(`[migrate] Ошибка в ${file}:`, err);
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user