Skip to content

Commit

Permalink
Added feature to alter tables on sync. Fixes sequelize#537
Browse files Browse the repository at this point in the history
  • Loading branch information
meyer9 committed Feb 10, 2017
1 parent 8cbd375 commit 5945d10
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/api/sequelize.md
Original file line number Diff line number Diff line change
Expand Up @@ -790,6 +790,7 @@ Sync all defined models to the DB.
| [options.schema='public'] | String | The schema that the tables should be created in. This can be overriden for each table in sequelize.define |
| [options.searchPath=DEFAULT] | String | An optional parameter to specify the schema search_path (Postgres only) |
| [options.hooks=true] | Boolean | If hooks is true then beforeSync, afterSync, beforBulkSync, afterBulkSync hooks will be called |
| [options.alter=false] | Boolean | Modify existing tables to fit models |


***
Expand Down
24 changes: 24 additions & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -1098,6 +1098,30 @@ class Model {
}
})
.then(() => this.QueryInterface.createTable(this.getTableName(options), attributes, options, this))
.then(() => {
if(options.alter) {
return this.QueryInterface.describeTable(this.getTableName(options))
.then((columns) => {
var self = this;
var changes = []; // array of promises to run
_.each(attributes, function(columnDesc, columnName) {
if(!columns[columnName]) {
changes.push(self.QueryInterface.addColumn(self.getTableName(options), columnName, attributes[columnName]));
}
});
_.each(columns, function(columnDesc, columnName) {
if(!attributes[columnName]) {
changes.push(self.QueryInterface.removeColumn(self.getTableName(options), columnName, options));
} else {
if(!attributes[columnName].primaryKey) {
changes.push(self.QueryInterface.changeColumn(self.getTableName(options), columnName, attributes[columnName]));
}
}
});
return Promise.all(changes);
});
}
})
.then(() => this.QueryInterface.showIndex(this.getTableName(options), options))
.then(indexes => {
// Assign an auto-generated name to indexes which are not named by the user
Expand Down

0 comments on commit 5945d10

Please sign in to comment.