Skip to content

Commit

Permalink
default values added for new columns when running autoupdate()
Browse files Browse the repository at this point in the history
Signed-off-by: Karan Raina <[email protected]>
  • Loading branch information
karanssj4 committed Feb 18, 2020
1 parent 754c1a0 commit bff6b46
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
3 changes: 2 additions & 1 deletion lib/migration.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,8 @@ function mixinMigration(PostgreSQL) {
model, self.column(model, propName), actualFields,
);
if (!found && self.propertyHasNotBeenDeleted(model, propName)) {
sql.push('ADD COLUMN ' + self.addPropertyToActual(model, propName));
// add new columns with default values
sql.push('ADD COLUMN ' + self.addPropertyToActual(model, propName) + self.columnDbDefault(model, propName));
}
});
if (sql.length > 0) {
Expand Down
33 changes: 32 additions & 1 deletion test/postgresql.migration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ describe('migrations', function() {
before(setup);

it('should run migration', function(done) {
db.automigrate(['UserDataWithIndexes', 'OrderData', 'DefaultUuid'], done);
db.automigrate(['UserDataWithIndexes', 'OrderData', 'DefaultUuid', 'DefaultValueAfterColumnAdd'], done);
});

it('UserDataWithIndexes should have correct indexes', function(done) {
Expand Down Expand Up @@ -109,6 +109,32 @@ describe('migrations', function() {
done();
});
});

it('should add default value for new required columns', async function() {
const DefaultValueAfterColumnAdd = await db.getModel('DefaultValueAfterColumnAdd');
await DefaultValueAfterColumnAdd.create({
name: 'name1',
});
await db.defineProperty('DefaultValueAfterColumnAdd', 'createdByAdmin', {
type: Boolean, required: true, default: true,
});
await db.defineProperty('DefaultValueAfterColumnAdd', 'birthDate', {
type: Date, required: true, default: '2020-02-18T16:50:24.746Z',
});
await db.defineProperty('DefaultValueAfterColumnAdd', 'pendingPeriod', {
type: Number, required: true, default: 10,
});
await db.autoupdate(['DefaultValueAfterColumnAdd']);
const res = await DefaultValueAfterColumnAdd.findOne();

assert.deepEqual(res.toJSON(), {
id: 1,
name: 'name1',
createdByAdmin: true,
birthDate: new Date('2020-02-18T16:50:24.746Z'),
pendingPeriod: 10,
});
});
});

function setup(done) {
Expand Down Expand Up @@ -172,6 +198,10 @@ function setup(done) {
}},
});

const DefaultValueAfterColumnAdd = db.define('DefaultValueAfterColumnAdd', {
name: String,
});

done();
}

Expand Down Expand Up @@ -230,3 +260,4 @@ function checkColumns(table, cb) {
cb(err, cols);
});
}

0 comments on commit bff6b46

Please sign in to comment.