forked from gimenete/sequelize-sync-diff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
76 lines (70 loc) · 2.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
var dbdiff = require("dbdiff");
module.exports = function (Sequelize, diffOptions) {
diffOptions = diffOptions || { level: "drop" };
if (Sequelize.prototype.syncDiff) return;
var sequelizeMethods = ["define"];
var modelMethods = ["belongsTo", "hasOne", "hasMany", "belongsToMany"];
sequelizeMethods.forEach(function (name) {
var func = Sequelize.prototype[name];
Sequelize.prototype[name] = function () {
var args = Array.prototype.slice.call(arguments);
this.diff_actions = this.diff_actions || [];
this.diff_actions.push({ method: name, args: args });
return func.apply(this, args);
};
});
modelMethods.forEach(function (name) {
var func = Sequelize.Model.prototype[name];
Sequelize.Model.prototype[name] = function () {
var args = Array.prototype.slice.call(arguments);
var sequelize = this.sequelize;
sequelize.diff_actions = sequelize.diff_actions || [];
sequelize.diff_actions.push({
method: name,
args: args,
model: this.name,
});
return func.apply(this, args);
};
});
Sequelize.prototype.syncDiff = function (options) {
var self = this;
const allOptions = { ...this.options, database: options.database };
var sequelize = new Sequelize(
options.database,
options.username,
options.password,
allOptions
);
this.diff_actions.forEach(function (action) {
if (!action.model) {
sequelize[action.method].apply(sequelize, action.args);
} else {
var model = sequelize.model(action.model);
action.args[0] = sequelize.model(action.args[0].name);
model[action.method].apply(model, action.args);
}
});
var selfOptions = {
dialect: self.options.dialect,
username: self.config.username,
password: self.config.password,
database: self.config.database,
port: self.config.port,
host: self.config.host,
dialectOptions: self.config.dialectOptions,
};
var diff = new dbdiff.DbDiff();
return sequelize
.sync({ force: true })
.then(function () {
return diff.compare(selfOptions, {
...selfOptions,
database: options.database,
});
})
.then(function () {
return diff.commands(diffOptions.level);
});
};
};