MCPcopy
hub / github.com/sequelize/sequelize / getModelsTopoSortedByForeignKey

Method getModelsTopoSortedByForeignKey

src/model-manager.js:48–99  ·  view source on GitHub ↗

* Returns an array that lists every model, sorted in order * of foreign key references: The first model is a model that is depended upon, * the last model is a model that is not depended upon. * * If there is a cyclic dependency, this returns null.

()

Source from the content-addressed store, hash-verified

46 * If there is a cyclic dependency, this returns null.
47 */
48 getModelsTopoSortedByForeignKey() {
49 const models = new Map();
50 const sorter = new Toposort();
51
52 for (const model of this.models) {
53 let deps = [];
54 let tableName = model.getTableName();
55
56 if (_.isObject(tableName)) {
57 tableName = `${tableName.schema}.${tableName.tableName}`;
58 }
59
60 models.set(tableName, model);
61
62 for (const attrName in model.rawAttributes) {
63 if (Object.prototype.hasOwnProperty.call(model.rawAttributes, attrName)) {
64 const attribute = model.rawAttributes[attrName];
65
66 if (attribute.references) {
67 let dep = attribute.references.model;
68
69 if (_.isObject(dep)) {
70 dep = `${dep.schema}.${dep.tableName}`;
71 }
72
73 deps.push(dep);
74 }
75 }
76 }
77
78 deps = deps.filter(dep => tableName !== dep);
79
80 sorter.add(tableName, deps);
81 }
82
83 let sorted;
84 try {
85 sorted = sorter.sort();
86 } catch (e) {
87 if (!e.message.startsWith('Cyclic dependency found.')) {
88 throw e;
89 }
90
91 return null;
92 }
93
94 return sorted
95 .map(modelName => {
96 return models.get(modelName);
97 })
98 .filter(Boolean);
99 }
100
101 /**
102 * Iterate over Models in an order suitable for e.g. creating tables.

Callers 4

forEachModelMethod · 0.95
syncMethod · 0.80
truncateMethod · 0.80
dropMethod · 0.80

Calls 4

getTableNameMethod · 0.80
setMethod · 0.65
getMethod · 0.65
addMethod · 0.45

Tested by

no test coverage detected