Add an optional models argument to automigrate/autoupdate

This commit is contained in:
Raymond Feng 2013-08-08 08:30:26 -07:00
parent 0a5c0ff77d
commit d3bf5c20ac
2 changed files with 47 additions and 18 deletions

View File

@ -412,27 +412,39 @@ DataSource.prototype.defineProperty = function (model, prop, params) {
* Drop each model table and re-create.
* This method make sense only for sql connectors.
*
* @param {String} or {[String]} Models to be migrated, if not present, apply to all models
*
* @warning All data will be lost! Use autoupdate if you need your data.
*/
DataSource.prototype.automigrate = function (cb) {
DataSource.prototype.automigrate = function (models, cb) {
this.freeze();
if (this.connector.automigrate) {
this.connector.automigrate(cb);
} else if (cb) {
cb();
this.connector.automigrate(models, cb);
} else {
if ((!cb) && ('function' === typeof models)) {
cb = models;
models = undefined;
}
cb && process.nextTick(cb);
}
};
/**
* Update existing database tables.
* This method make sense only for sql connectors.
*
* @param {String} or {[String]} Models to be migrated, if not present, apply to all models
*/
DataSource.prototype.autoupdate = function (cb) {
DataSource.prototype.autoupdate = function (models, cb) {
this.freeze();
if (this.connector.autoupdate) {
this.connector.autoupdate(cb);
} else if (cb) {
cb();
this.connector.autoupdate(models, cb);
} else {
if ((!cb) && ('function' === typeof models)) {
cb = models;
models = undefined;
}
cb && process.nextTick(cb);
}
};

View File

@ -267,11 +267,27 @@ BaseSQL.prototype.disconnect = function disconnect() {
this.client.end();
};
BaseSQL.prototype.automigrate = function (cb) {
/**
* Recreate the tables for the given models
* @param models A model name or an array of model names, if not present, apply to all models defined in the connector
* @param cb Callback function
*/
BaseSQL.prototype.automigrate = function (models, cb) {
var self = this;
var wait = 0;
Object.keys(this._models).forEach(function (model) {
wait += 1;
if ((!cb) && ('function' === typeof models)) {
cb = models;
models = undefined;
}
// First argument is a model name
if ('string' === typeof models) {
models = [models];
}
models = models || Object.keys(this._models);
models.forEach(function (model) {
if (model in self._models) {
wait++;
self.dropTable(model, function () {
// console.log('drop', model);
self.createTable(model, function (err) {
@ -280,6 +296,7 @@ BaseSQL.prototype.automigrate = function (cb) {
done();
});
});
}
});
if (wait === 0) cb();