Skip to content

Commit

Permalink
Fix loopbackio#123: Set default value during autoupdate.
Browse files Browse the repository at this point in the history
This is a mergeable update to loopbackio#153 that also respects dbDefault.
  • Loading branch information
STRML committed Sep 12, 2016
1 parent 7273f41 commit 9dacaab
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
14 changes: 11 additions & 3 deletions lib/migration.js
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,8 @@ function mixinMigration(PostgreSQL) {
var prop = this.getModelDefinition(model).properties[propName];
var sqlCommand = self.columnEscaped(model, propName)
+ ' ' + self.columnDataType(model, propName) +
(self.isNullable(prop) ? '' : ' NOT NULL');
(self.isNullable(prop) ? '' : ' NOT NULL') +
self.columnDbDefault(model, propName);
return sqlCommand;
};

Expand Down Expand Up @@ -496,7 +497,8 @@ function mixinMigration(PostgreSQL) {
};

/*!
* Get the database-default value for column from given model property
* Get the database-default value for column from given model property.
* Falls back to LDL's prop.default.
*
* @param {String} model The model name
* @param {String} property The property name
Expand All @@ -505,8 +507,14 @@ function mixinMigration(PostgreSQL) {
PostgreSQL.prototype.columnDbDefault = function(model, property) {
var columnMetadata = this.columnMetadata(model, property);
var colDefault = columnMetadata && columnMetadata.dbDefault;
if (!colDefault) {
var prop = this.getModelDefinition(model).properties[property];
if (prop.hasOwnProperty('default')) {
colDefault = String(this.escapeValue(prop.default));
}
}

return colDefault ? (' DEFAULT ' + columnMetadata.dbDefault) : '';
return colDefault ? (' DEFAULT ' + colDefault) : '';
};

/*!
Expand Down
5 changes: 2 additions & 3 deletions test/postgresql.migration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ describe('migrations', function() {
before(setup);

it('should run migration', function(done) {
db.automigrate('UserDataWithIndexes', function() {
done();
});
db.automigrate('UserDataWithIndexes', done);
});

it('UserDataWithIndexes should have correct indexes', function(done) {
Expand Down Expand Up @@ -89,6 +87,7 @@ function setup(done) {
birthDate: Date,
pendingPeriod: Number,
createdByAdmin: Boolean,
deleted: {type: Boolean, required: true, default: false},
}, {
indexes: {
udwi_index1: {
Expand Down

0 comments on commit 9dacaab

Please sign in to comment.