Skip to content

Commit

Permalink
Insert lock row fix during migration (#4865)
Browse files Browse the repository at this point in the history
(cherry picked from commit 540ab8c)
  • Loading branch information
OlivierCavadenti committed Dec 3, 2021
1 parent 54934ba commit 96362d4
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 6 deletions.
2 changes: 1 addition & 1 deletion lib/migrations/migrate/Migrator.js
Expand Up @@ -327,7 +327,7 @@ class Migrator {
.where('is_locked', '=', 0)
.update({ is_locked: 1 })
.then((rowCount) => {
if (rowCount != 1) {
if (rowCount !== 1) {
throw new Error('Migration table is already locked');
}
});
Expand Down
11 changes: 6 additions & 5 deletions lib/migrations/migrate/table-creator.js
Expand Up @@ -55,11 +55,12 @@ function _createMigrationLockTable(tableName, schemaName, trxOrKnex) {
function _insertLockRowIfNeeded(tableName, schemaName, trxOrKnex) {
const lockTableWithSchema = getLockTableNameWithSchema(tableName, schemaName);
return trxOrKnex
.from(trxOrKnex.raw('?? (??)', [lockTableWithSchema, 'is_locked']))
.insert(function () {
return this.select(trxOrKnex.raw('?', [0])).whereNotExists(function () {
return this.select('*').from(lockTableWithSchema);
});
.select('*')
.from(lockTableWithSchema)
.then((data) => {
return !data.length
? trxOrKnex.from(lockTableWithSchema).insert({ is_locked: 0 })
: null;
});
}

Expand Down
32 changes: 32 additions & 0 deletions test/integration2/migrate/migration-integration.spec.js
Expand Up @@ -25,6 +25,9 @@ const {
} = require('../../util/db-helpers');
const { assertNumber } = require('../../util/assertHelper');
const { getAllDbs, getKnexForDb } = require('../util/knex-instance-provider');
const {
ensureTable,
} = require('../../../lib/migrations/migrate/table-creator');

describe('Migrations', function () {
getAllDbs().forEach((db) => {
Expand Down Expand Up @@ -1243,6 +1246,35 @@ describe('Migrations', function () {
}
});
});

describe('Test lock row', async () => {
beforeEach(async () => {
await knex.schema.dropTableIfExists('test_lock');
});

it('should insert is_locked value to 1 if lock table not exists', async () => {
const result = await ensureTable('test', undefined, knex);

expect(!!(result || result.length)).is.true;
const data = await knex('test_lock').select('*');
expect(data[0]).to.have.property('is_locked');
expect(Number.parseInt(data[0].is_locked)).to.not.be.ok;
});

it('should is_locked value still be 1 if row already exists', async () => {
await knex.schema.createTable('test_lock', (t) => {
t.increments('index').primary();
t.integer('is_locked');
});
await knex('test_lock').insert({ is_locked: 1 });

const result = await ensureTable('test', undefined, knex);
expect(result).to.false;
const data = await knex('test_lock').select('*');
expect(data[0]).to.have.property('is_locked');
expect(Number.parseInt(data[0].is_locked)).to.be.ok;
});
});
});
});
});

0 comments on commit 96362d4

Please sign in to comment.