forked from sequelize/sequelize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel-manager.js
98 lines (77 loc) · 2.25 KB
/
model-manager.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
'use strict';
var Toposort = require('toposort-class')
, _ = require('lodash');
module.exports = (function() {
var ModelManager = function(sequelize) {
this.daos = [];
this.sequelize = sequelize;
};
ModelManager.prototype.addDAO = function(dao) {
this.daos.push(dao);
this.sequelize.models[dao.name] = dao;
return dao;
};
ModelManager.prototype.removeDAO = function(dao) {
this.daos = this.daos.filter(function(_dao) {
return _dao.name !== dao.name;
});
delete this.sequelize.models[dao.name];
};
ModelManager.prototype.getDAO = function(daoName, options) {
options = _.defaults(options || {}, {
attribute: 'name'
});
var dao = this.daos.filter(function(dao) {
return dao[options.attribute] === daoName;
});
return !!dao ? dao[0] : null;
};
ModelManager.prototype.__defineGetter__('all', function() {
return this.daos;
});
/**
* Iterate over DAOs in an order suitable for e.g. creating tables. Will
* take foreign key constraints into account so that dependencies are visited
* before dependents.
*/
ModelManager.prototype.forEachDAO = function(iterator, options) {
var daos = {}
, sorter = new Toposort()
, sorted
, dep;
options = _.defaults(options || {}, {
reverse: true
});
this.daos.forEach(function(dao) {
var deps = []
, tableName = dao.getTableName();
if (_.isObject(tableName)) {
tableName = tableName.schema + '.' + tableName.tableName;
}
daos[tableName] = dao;
for (var attrName in dao.rawAttributes) {
if (dao.rawAttributes.hasOwnProperty(attrName)) {
if (dao.rawAttributes[attrName].references) {
dep = dao.rawAttributes[attrName].references;
if (_.isObject(dep)) {
dep = dep.schema + '.' + dep.tableName;
}
deps.push(dep);
}
}
}
deps = deps.filter(function(dep) {
return tableName !== dep;
});
sorter.add(tableName, deps);
});
sorted = sorter.sort();
if (options.reverse) {
sorted = sorted.reverse();
}
sorted.forEach(function(name) {
iterator(daos[name], name);
});
};
return ModelManager;
})();