Skip to content

Commit d21a622

Browse files
author
Jaka Purg
committed
Check for loading old migrations after new one on prod env
1 parent c27a541 commit d21a622

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

.example.env

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,8 @@ DB_HOST=
22
DB_PORT=
33
DB_USER=
44
DB_PASSWORD=
5-
DB_DATABASE=
5+
DB_DATABASE=
6+
7+
8+
# Change to 'prod' to prevent not loaded migrations with lower timestamp to be run after loaded migrations with higher timestamp
9+
MODE=dev

src/migrations.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ import * as path from 'path';
33
import { promisify } from 'util';
44
import { QueryFunction } from 'mysql';
55

6+
require('dotenv').config();
7+
8+
69
/**
710
* Database connection interface
811
*/
@@ -207,6 +210,17 @@ export class Migration {
207210
const notLoadedScripts = files.filter((file) => !loadedScripts.find((loadedScripts) => loadedScripts.fileName === file));
208211

209212
const sortedNotLoadedScripts = notLoadedScripts.sort(this.sortFiles);
213+
214+
if(loadedScripts.length && sortedNotLoadedScripts.length) {
215+
const lastLoadedScript = loadedScripts[loadedScripts.length - 1];
216+
// Get timestamp from filename of both scripts
217+
const lastLoadedScriptTimestamp = lastLoadedScript.fileName.match(/^(\d*)-/)[1];
218+
const firstNotLoadedScriptTimestamp = sortedNotLoadedScripts[0].match(/^(\d*)-/)[1];
219+
if(process.env.MODE === 'prod' && firstNotLoadedScriptTimestamp < lastLoadedScriptTimestamp) {
220+
throw new Error('Check your migration scripts! You are trying to load a script with a lower timestamp than the last loaded script!');
221+
}
222+
}
223+
210224
const fileArr = [...loadedScripts.map((script) => script.fileName), ...sortedNotLoadedScripts];
211225

212226
this.writeLog(`Found migration scripts: ${fileArr.join(', ')}`);

0 commit comments

Comments
 (0)