Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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', {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

defineProperty is a sync function I think, see its definition

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);
});
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extra EOL at EOF, please remove.