@nocobase/database 0.9.1-alpha.1 → 0.9.2-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/lib/collection-group-manager.d.ts +13 -0
  2. package/lib/collection-group-manager.js +91 -0
  3. package/lib/collection-importer.js +0 -24
  4. package/lib/collection.d.ts +26 -4
  5. package/lib/collection.js +190 -234
  6. package/lib/database-utils/index.js +3 -15
  7. package/lib/database.d.ts +9 -0
  8. package/lib/database.js +171 -299
  9. package/lib/decorators/must-have-filter-decorator.js +0 -7
  10. package/lib/decorators/transaction-decorator.js +5 -18
  11. package/lib/errors/identifier-error.js +0 -3
  12. package/lib/features/ReferencesMap.js +1 -14
  13. package/lib/features/referential-integrity-check.js +7 -21
  14. package/lib/field-repository/array-field-repository.js +5 -45
  15. package/lib/fields/array-field.js +0 -13
  16. package/lib/fields/belongs-to-field.js +24 -50
  17. package/lib/fields/belongs-to-many-field.js +29 -47
  18. package/lib/fields/boolean-field.js +0 -7
  19. package/lib/fields/context-field.js +2 -23
  20. package/lib/fields/date-field.d.ts +4 -0
  21. package/lib/fields/date-field.js +15 -7
  22. package/lib/fields/field.js +32 -85
  23. package/lib/fields/has-many-field.js +16 -49
  24. package/lib/fields/has-one-field.js +18 -52
  25. package/lib/fields/index.js +0 -44
  26. package/lib/fields/json-field.js +0 -12
  27. package/lib/fields/number-field.js +0 -23
  28. package/lib/fields/password-field.js +8 -35
  29. package/lib/fields/radio-field.js +0 -18
  30. package/lib/fields/relation-field.js +4 -16
  31. package/lib/fields/set-field.js +0 -8
  32. package/lib/fields/sort-field.js +84 -73
  33. package/lib/fields/string-field.js +0 -7
  34. package/lib/fields/text-field.js +0 -7
  35. package/lib/fields/time-field.js +0 -7
  36. package/lib/fields/uid-field.js +4 -22
  37. package/lib/fields/uuid-field.js +3 -12
  38. package/lib/fields/virtual-field.js +0 -7
  39. package/lib/filter-match.js +7 -22
  40. package/lib/filter-parser.js +38 -102
  41. package/lib/index.d.ts +3 -0
  42. package/lib/index.js +36 -42
  43. package/lib/inherited-collection.js +15 -62
  44. package/lib/inherited-map.js +7 -48
  45. package/lib/listeners/adjacency-list.d.ts +3 -0
  46. package/lib/listeners/adjacency-list.js +91 -0
  47. package/lib/listeners/index.d.ts +2 -0
  48. package/lib/listeners/index.js +12 -0
  49. package/lib/magic-attribute-model.js +58 -114
  50. package/lib/migration.js +7 -28
  51. package/lib/mock-database.d.ts +4 -4
  52. package/lib/mock-database.js +15 -18
  53. package/lib/model-hook.js +4 -35
  54. package/lib/model.js +12 -54
  55. package/lib/operators/array.js +2 -32
  56. package/lib/operators/association.js +0 -6
  57. package/lib/operators/boolean.js +0 -6
  58. package/lib/operators/child-collection.d.ts +2 -0
  59. package/lib/operators/child-collection.js +32 -0
  60. package/lib/operators/date.js +123 -60
  61. package/lib/operators/empty.js +3 -32
  62. package/lib/operators/eq.d.ts +2 -0
  63. package/lib/operators/eq.js +26 -0
  64. package/lib/operators/index.js +4 -7
  65. package/lib/operators/ne.js +5 -5
  66. package/lib/operators/notIn.js +0 -5
  67. package/lib/operators/string.js +0 -11
  68. package/lib/operators/utils.js +0 -6
  69. package/lib/options-parser.d.ts +1 -1
  70. package/lib/options-parser.js +47 -107
  71. package/lib/playground.js +0 -4
  72. package/lib/query-interface/mysql-query-interface.d.ts +18 -0
  73. package/lib/query-interface/mysql-query-interface.js +88 -0
  74. package/lib/query-interface/postgres-query-interface.d.ts +14 -0
  75. package/lib/query-interface/postgres-query-interface.js +99 -0
  76. package/lib/query-interface/query-interface-builder.d.ts +2 -0
  77. package/lib/query-interface/query-interface-builder.js +18 -0
  78. package/lib/query-interface/query-interface.d.ts +21 -0
  79. package/lib/query-interface/query-interface.js +48 -0
  80. package/lib/query-interface/sqlite-query-interface.d.ts +17 -0
  81. package/lib/query-interface/sqlite-query-interface.js +89 -0
  82. package/lib/relation-repository/belongs-to-many-repository.js +21 -78
  83. package/lib/relation-repository/belongs-to-repository.js +0 -3
  84. package/lib/relation-repository/hasmany-repository.js +8 -44
  85. package/lib/relation-repository/hasone-repository.js +0 -3
  86. package/lib/relation-repository/multiple-relation-repository.js +16 -68
  87. package/lib/relation-repository/relation-repository.js +5 -42
  88. package/lib/relation-repository/single-relation-repository.js +6 -43
  89. package/lib/repository.d.ts +1 -0
  90. package/lib/repository.js +36 -182
  91. package/lib/sql-parser/index.js +10527 -0
  92. package/lib/sql-parser/sql.pegjs +1297 -0
  93. package/lib/sync-runner.d.ts +1 -1
  94. package/lib/sync-runner.js +26 -64
  95. package/lib/update-associations.js +58 -157
  96. package/lib/update-guard.js +10 -49
  97. package/lib/utils.js +16 -54
  98. package/lib/value-parsers/array-value-parser.js +3 -21
  99. package/lib/value-parsers/base-value-parser.js +0 -13
  100. package/lib/value-parsers/boolean-value-parser.js +4 -10
  101. package/lib/value-parsers/date-value-parser.js +0 -23
  102. package/lib/value-parsers/index.js +0 -10
  103. package/lib/value-parsers/json-value-parser.js +0 -7
  104. package/lib/value-parsers/number-value-parser.js +0 -9
  105. package/lib/value-parsers/string-value-parser.js +3 -20
  106. package/lib/value-parsers/to-many-value-parser.js +1 -42
  107. package/lib/value-parsers/to-one-value-parser.js +0 -14
  108. package/lib/view/field-type-map.d.ts +47 -0
  109. package/lib/view/field-type-map.js +56 -0
  110. package/lib/view/view-inference.d.ts +31 -0
  111. package/lib/view/view-inference.js +92 -0
  112. package/lib/view-collection.d.ts +6 -0
  113. package/lib/view-collection.js +24 -0
  114. package/package.json +4 -3
  115. package/src/__tests__/collection.test.ts +44 -0
  116. package/src/__tests__/fields/date.test.ts +75 -0
  117. package/src/__tests__/fields/sort-field.test.ts +100 -0
  118. package/src/__tests__/filter.test.ts +60 -0
  119. package/src/__tests__/group.test.ts +50 -0
  120. package/src/__tests__/inhertits/collection-inherits.test.ts +114 -0
  121. package/src/__tests__/operator/date-operator.test.ts +244 -98
  122. package/src/__tests__/operator/eq.test.ts +76 -0
  123. package/src/__tests__/operator/ne.test.ts +19 -1
  124. package/src/__tests__/relation-repository/belongs-to-many-repository.test.ts +82 -0
  125. package/src/__tests__/repository/find.test.ts +33 -0
  126. package/src/__tests__/repository.test.ts +88 -0
  127. package/src/__tests__/sql-parser.test.ts +13 -0
  128. package/src/__tests__/tree.test.ts +217 -0
  129. package/src/__tests__/view/list-view.test.ts +34 -0
  130. package/src/__tests__/view/view-collection.test.ts +199 -0
  131. package/src/__tests__/view/view-inference.test.ts +145 -0
  132. package/src/__tests__/view/view-repository.test.ts +67 -0
  133. package/src/collection-group-manager.ts +94 -0
  134. package/src/collection.ts +126 -16
  135. package/src/database-utils/index.ts +1 -0
  136. package/src/database.ts +98 -17
  137. package/src/features/ReferencesMap.ts +3 -2
  138. package/src/fields/belongs-to-many-field.ts +23 -4
  139. package/src/fields/date-field.ts +18 -0
  140. package/src/fields/field.ts +17 -7
  141. package/src/fields/json-field.ts +1 -0
  142. package/src/fields/sort-field.ts +90 -29
  143. package/src/filter-parser.ts +2 -1
  144. package/src/index.ts +3 -1
  145. package/src/listeners/adjacency-list.ts +60 -0
  146. package/src/listeners/index.ts +7 -0
  147. package/src/mock-database.ts +14 -2
  148. package/src/model.ts +4 -0
  149. package/src/operators/child-collection.ts +24 -0
  150. package/src/operators/date.ts +108 -24
  151. package/src/operators/eq.ts +14 -0
  152. package/src/operators/index.ts +2 -0
  153. package/src/operators/ne.ts +12 -7
  154. package/src/options-parser.ts +25 -11
  155. package/src/query-interface/mysql-query-interface.ts +72 -0
  156. package/src/query-interface/postgres-query-interface.ts +103 -0
  157. package/src/query-interface/query-interface-builder.ts +14 -0
  158. package/src/query-interface/query-interface.ts +43 -0
  159. package/src/query-interface/sqlite-query-interface.ts +79 -0
  160. package/src/relation-repository/belongs-to-many-repository.ts +20 -1
  161. package/src/relation-repository/hasmany-repository.ts +5 -3
  162. package/src/relation-repository/multiple-relation-repository.ts +13 -1
  163. package/src/relation-repository/single-relation-repository.ts +2 -0
  164. package/src/repository.ts +6 -13
  165. package/src/sql-parser/index.js +10698 -0
  166. package/src/sql-parser/readme.md +2 -0
  167. package/src/sql-parser/sql.pegjs +1297 -0
  168. package/src/sync-runner.ts +27 -32
  169. package/src/update-associations.ts +26 -22
  170. package/src/utils.ts +4 -3
  171. package/src/view/field-type-map.ts +56 -0
  172. package/src/view/view-inference.ts +106 -0
  173. package/src/view-collection.ts +21 -0
package/lib/collection.js CHANGED
@@ -4,103 +4,109 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.Collection = void 0;
7
-
8
7
  function _deepmerge() {
9
8
  const data = _interopRequireDefault(require("deepmerge"));
10
-
11
9
  _deepmerge = function _deepmerge() {
12
10
  return data;
13
11
  };
14
-
15
12
  return data;
16
13
  }
17
-
18
14
  function _events() {
19
15
  const data = require("events");
20
-
21
16
  _events = function _events() {
22
17
  return data;
23
18
  };
24
-
25
19
  return data;
26
20
  }
27
-
28
21
  function _lodash() {
29
22
  const data = _interopRequireDefault(require("lodash"));
30
-
31
23
  _lodash = function _lodash() {
32
24
  return data;
33
25
  };
34
-
35
26
  return data;
36
27
  }
37
-
38
28
  function _sequelize() {
39
29
  const data = require("sequelize");
40
-
41
30
  _sequelize = function _sequelize() {
42
31
  return data;
43
32
  };
44
-
45
33
  return data;
46
34
  }
47
-
48
35
  var _model = require("./model");
49
-
50
36
  var _repository = require("./repository");
51
-
52
37
  var _utils = require("./utils");
53
-
54
38
  const _excluded = ["name"],
55
- _excluded2 = ["name"];
56
-
39
+ _excluded2 = ["name"];
57
40
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
58
-
59
41
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
60
-
61
42
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
62
-
63
43
  function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
64
-
65
44
  function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
66
-
67
45
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
68
-
69
46
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
70
-
71
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
72
-
47
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
48
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
49
+ function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
73
50
  function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
74
-
75
51
  function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
76
-
77
- function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
78
-
52
+ function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
79
53
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
80
-
81
54
  function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
82
-
83
55
  function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
84
-
85
56
  function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
86
-
87
57
  class Collection extends _events().EventEmitter {
88
58
  get filterTargetKey() {
89
- return _lodash().default.get(this.options, 'filterTargetKey', this.model.primaryKeyAttribute);
59
+ let targetKey = _lodash().default.get(this.options, 'filterTargetKey', this.model.primaryKeyAttribute);
60
+ if (!targetKey && this.model.rawAttributes['id']) {
61
+ return 'id';
62
+ }
63
+ return targetKey;
90
64
  }
91
-
92
65
  get name() {
93
66
  return this.options.name;
94
67
  }
95
-
96
68
  get titleField() {
97
69
  return this.options.titleField || this.model.primaryKeyAttribute;
98
70
  }
99
-
100
71
  get db() {
101
72
  return this.context.database;
102
73
  }
103
-
74
+ get treeParentField() {
75
+ var _iterator = _createForOfIteratorHelper(this.fields),
76
+ _step;
77
+ try {
78
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
79
+ const _step$value = _slicedToArray(_step.value, 2),
80
+ _ = _step$value[0],
81
+ field = _step$value[1];
82
+ if (field.options.treeParent) {
83
+ return field;
84
+ }
85
+ }
86
+ } catch (err) {
87
+ _iterator.e(err);
88
+ } finally {
89
+ _iterator.f();
90
+ }
91
+ }
92
+ get treeChildrenField() {
93
+ var _iterator2 = _createForOfIteratorHelper(this.fields),
94
+ _step2;
95
+ try {
96
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
97
+ const _step2$value = _slicedToArray(_step2.value, 2),
98
+ _ = _step2$value[0],
99
+ field = _step2$value[1];
100
+ if (field.options.treeChildren) {
101
+ return field;
102
+ }
103
+ }
104
+ } catch (err) {
105
+ _iterator2.e(err);
106
+ } finally {
107
+ _iterator2.f();
108
+ }
109
+ }
104
110
  constructor(options, context) {
105
111
  super();
106
112
  this.options = void 0;
@@ -115,52 +121,46 @@ class Collection extends _events().EventEmitter {
115
121
  this.bindFieldEventListener();
116
122
  this.modelInit();
117
123
  this.db.modelCollection.set(this.model, this);
118
- this.db.tableNameCollectionMap.set(this.model.tableName, this);
119
-
124
+ // set tableName to collection map
125
+ // the form of key is `${schema}.${tableName}` if schema exists
126
+ // otherwise is `${tableName}`
127
+ this.db.tableNameCollectionMap.set(this.getTableNameWithSchemaAsString(), this);
120
128
  if (!options.inherits) {
121
129
  this.setFields(options.fields);
122
130
  }
123
-
124
131
  this.setRepository(options.repository);
125
132
  this.setSortable(options.sortable);
126
133
  }
127
-
128
134
  checkOptions(options) {
129
135
  (0, _utils.checkIdentifier)(options.name);
130
136
  this.checkTableName();
131
137
  }
132
-
133
138
  checkTableName() {
134
139
  const tableName = this.tableName();
135
-
136
- var _iterator = _createForOfIteratorHelper(this.db.collections),
137
- _step;
138
-
140
+ var _iterator3 = _createForOfIteratorHelper(this.db.collections),
141
+ _step3;
139
142
  try {
140
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
141
- const _step$value = _slicedToArray(_step.value, 2),
142
- k = _step$value[0],
143
- collection = _step$value[1];
144
-
145
- if (collection.name != this.options.name && tableName === collection.tableName()) {
143
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
144
+ const _step3$value = _slicedToArray(_step3.value, 2),
145
+ k = _step3$value[0],
146
+ collection = _step3$value[1];
147
+ if (collection.name != this.options.name && tableName === collection.tableName() && collection.collectionSchema() === this.collectionSchema()) {
146
148
  throw new Error(`collection ${collection.name} and ${this.name} have same tableName "${tableName}"`);
147
149
  }
148
150
  }
149
151
  } catch (err) {
150
- _iterator.e(err);
152
+ _iterator3.e(err);
151
153
  } finally {
152
- _iterator.f();
154
+ _iterator3.f();
153
155
  }
154
156
  }
155
-
156
157
  tableName() {
157
158
  const _this$options = this.options,
158
- name = _this$options.name,
159
- tableName = _this$options.tableName;
159
+ name = _this$options.name,
160
+ tableName = _this$options.tableName;
160
161
  const tName = tableName || name;
161
- return this.db.options.underscored ? (0, _utils.snakeCase)(tName) : tName;
162
+ return this.options.underscored ? (0, _utils.snakeCase)(tName) : tName;
162
163
  }
163
-
164
164
  sequelizeModelOptions() {
165
165
  const name = this.options.name;
166
166
  return _objectSpread(_objectSpread({}, _lodash().default.omit(this.options, ['name', 'fields', 'model', 'targetKey'])), {}, {
@@ -172,155 +172,141 @@ class Collection extends _events().EventEmitter {
172
172
  /**
173
173
  * TODO
174
174
  */
175
-
176
-
177
175
  modelInit() {
178
176
  if (this.model) {
179
177
  return;
180
178
  }
181
-
182
179
  const _this$options2 = this.options,
183
- name = _this$options2.name,
184
- model = _this$options2.model,
185
- _this$options2$autoGe = _this$options2.autoGenId,
186
- autoGenId = _this$options2$autoGe === void 0 ? true : _this$options2$autoGe;
180
+ name = _this$options2.name,
181
+ model = _this$options2.model,
182
+ _this$options2$autoGe = _this$options2.autoGenId,
183
+ autoGenId = _this$options2$autoGe === void 0 ? true : _this$options2$autoGe;
187
184
  let M = _model.Model;
188
-
189
185
  if (this.context.database.sequelize.isDefined(name)) {
190
186
  const m = this.context.database.sequelize.model(name);
191
-
192
187
  if (m.isThrough) {
193
188
  // @ts-ignore
194
- this.model = m; // @ts-ignore
195
-
196
- this.model.database = this.context.database; // @ts-ignore
197
-
189
+ this.model = m;
190
+ // @ts-ignore
191
+ this.model.database = this.context.database;
192
+ // @ts-ignore
198
193
  this.model.collection = this;
199
194
  return;
200
195
  }
201
196
  }
202
-
203
197
  if (typeof model === 'string') {
204
198
  M = this.context.database.models.get(model) || _model.Model;
205
199
  } else if (model) {
206
200
  M = model;
207
- } // @ts-ignore
208
-
209
-
201
+ }
202
+ // @ts-ignore
210
203
  this.model = class extends M {};
211
204
  this.model.init(null, this.sequelizeModelOptions());
212
-
213
205
  if (!autoGenId) {
214
206
  this.model.removeAttribute('id');
215
- } // @ts-ignore
216
-
217
-
218
- this.model.database = this.context.database; // @ts-ignore
219
-
207
+ }
208
+ // @ts-ignore
209
+ this.model.database = this.context.database;
210
+ // @ts-ignore
220
211
  this.model.collection = this;
221
212
  }
222
-
223
213
  setRepository(repository) {
224
214
  let repo = _repository.Repository;
225
-
226
215
  if (typeof repository === 'string') {
227
216
  repo = this.context.database.repositories.get(repository) || _repository.Repository;
228
217
  }
229
-
230
218
  this.repository = new repo(this);
231
219
  }
232
-
233
220
  bindFieldEventListener() {
234
221
  this.on('field.afterAdd', field => {
235
222
  field.bind();
236
223
  });
237
224
  this.on('field.afterRemove', field => {
238
225
  field.unbind();
226
+ this.db.emit('field.afterRemove', field);
239
227
  });
240
228
  }
241
-
242
229
  forEachField(callback) {
243
230
  return [...this.fields.values()].forEach(callback);
244
231
  }
245
-
246
232
  findField(callback) {
247
233
  return [...this.fields.values()].find(callback);
248
234
  }
249
-
250
235
  hasField(name) {
251
236
  return this.fields.has(name);
252
237
  }
253
-
254
238
  getField(name) {
255
239
  return this.fields.get(name);
256
240
  }
257
-
258
241
  addField(name, options) {
259
242
  return this.setField(name, options);
260
243
  }
261
-
262
244
  checkFieldType(name, options) {
263
- if (!this.db.options.underscored) {
245
+ if (!this.options.underscored) {
264
246
  return;
265
247
  }
266
-
267
248
  const fieldName = options.field || (0, _utils.snakeCase)(name);
268
249
  const field = this.findField(f => {
269
250
  if (f.name === name) {
270
251
  return false;
271
252
  }
272
-
273
253
  if (f.field) {
274
254
  return f.field === fieldName;
275
255
  }
276
-
277
256
  return (0, _utils.snakeCase)(f.name) === fieldName;
278
257
  });
279
-
280
258
  if (!field) {
281
259
  return;
282
260
  }
283
-
284
261
  if (options.type !== field.type) {
285
262
  throw new Error(`fields with same column must be of the same type ${JSON.stringify(options)}`);
286
263
  }
287
264
  }
288
-
289
265
  setField(name, options) {
290
266
  (0, _utils.checkIdentifier)(name);
291
267
  this.checkFieldType(name, options);
292
268
  const database = this.context.database;
269
+ if (options.source) {
270
+ const _options$source$split = options.source.split('.'),
271
+ _options$source$split2 = _slicedToArray(_options$source$split, 2),
272
+ sourceCollectionName = _options$source$split2[0],
273
+ sourceFieldName = _options$source$split2[1];
274
+ const sourceCollection = this.db.collections.get(sourceCollectionName);
275
+ if (!sourceCollection) {
276
+ throw new Error(`source collection "${sourceCollectionName}" not found`);
277
+ }
278
+ const sourceField = sourceCollection.fields.get(sourceFieldName);
279
+ options = _objectSpread(_objectSpread({}, sourceField.options), options);
280
+ }
281
+ this.emit('field.beforeAdd', name, options, {
282
+ collection: this
283
+ });
293
284
  const field = database.buildField(_objectSpread({
294
285
  name
295
286
  }, options), _objectSpread(_objectSpread({}, this.context), {}, {
296
287
  collection: this
297
288
  }));
298
289
  const oldField = this.fields.get(name);
299
-
300
290
  if (oldField && oldField.options.inherit && field.typeToString() != oldField.typeToString()) {
301
291
  throw new Error(`Field type conflict: cannot set "${name}" on "${this.name}" to ${options.type}, parent "${name}" type is ${oldField.options.type}`);
302
292
  }
303
-
304
293
  if (this.options.autoGenId !== false && options.primaryKey) {
305
294
  this.model.removeAttribute('id');
306
295
  }
307
-
308
296
  this.removeField(name);
309
297
  this.fields.set(name, field);
310
- this.emit('field.afterAdd', field); // refresh children models
311
-
298
+ this.emit('field.afterAdd', field);
299
+ // refresh children models
312
300
  if (this.isParent()) {
313
- var _iterator2 = _createForOfIteratorHelper(this.context.database.inheritanceMap.getChildren(this.name, {
314
- deep: false
315
- })),
316
- _step2;
317
-
301
+ var _iterator4 = _createForOfIteratorHelper(this.context.database.inheritanceMap.getChildren(this.name, {
302
+ deep: false
303
+ })),
304
+ _step4;
318
305
  try {
319
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
320
- const child = _step2.value;
306
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
307
+ const child = _step4.value;
321
308
  const childCollection = this.db.getCollection(child);
322
309
  const existField = childCollection.getField(name);
323
-
324
310
  if (!existField || existField.options.inherit) {
325
311
  childCollection.setField(name, _objectSpread(_objectSpread({}, options), {}, {
326
312
  inherit: true
@@ -328,155 +314,127 @@ class Collection extends _events().EventEmitter {
328
314
  }
329
315
  }
330
316
  } catch (err) {
331
- _iterator2.e(err);
317
+ _iterator4.e(err);
332
318
  } finally {
333
- _iterator2.f();
319
+ _iterator4.f();
334
320
  }
335
321
  }
336
-
337
322
  return field;
338
323
  }
339
-
340
324
  setFields(fields, resetFields = true) {
341
325
  if (!Array.isArray(fields)) {
342
326
  return;
343
327
  }
344
-
345
328
  if (resetFields) {
346
329
  this.resetFields();
347
330
  }
348
-
349
- var _iterator3 = _createForOfIteratorHelper(fields),
350
- _step3;
351
-
331
+ var _iterator5 = _createForOfIteratorHelper(fields),
332
+ _step5;
352
333
  try {
353
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
354
- const _ref = _step3.value;
355
-
334
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
335
+ const _ref = _step5.value;
356
336
  const name = _ref.name,
357
- options = _objectWithoutProperties(_ref, _excluded);
358
-
337
+ options = _objectWithoutProperties(_ref, _excluded);
359
338
  this.addField(name, options);
360
339
  }
361
340
  } catch (err) {
362
- _iterator3.e(err);
341
+ _iterator5.e(err);
363
342
  } finally {
364
- _iterator3.f();
343
+ _iterator5.f();
365
344
  }
366
345
  }
367
-
368
346
  resetFields() {
369
347
  const fieldNames = this.fields.keys();
370
-
371
- var _iterator4 = _createForOfIteratorHelper(fieldNames),
372
- _step4;
373
-
348
+ var _iterator6 = _createForOfIteratorHelper(fieldNames),
349
+ _step6;
374
350
  try {
375
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
376
- const fieldName = _step4.value;
351
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
352
+ const fieldName = _step6.value;
377
353
  this.removeField(fieldName);
378
354
  }
379
355
  } catch (err) {
380
- _iterator4.e(err);
356
+ _iterator6.e(err);
381
357
  } finally {
382
- _iterator4.f();
358
+ _iterator6.f();
383
359
  }
384
360
  }
385
-
386
361
  remove() {
387
362
  this.context.database.removeCollection(this.name);
388
363
  }
389
-
390
364
  removeFromDb(options) {
391
365
  var _this = this;
392
-
393
366
  return _asyncToGenerator(function* () {
394
- if (yield _this.existsInDb({
367
+ if (!_this.isView() && (yield _this.existsInDb({
395
368
  transaction: options === null || options === void 0 ? void 0 : options.transaction
396
- })) {
369
+ }))) {
397
370
  const queryInterface = _this.db.sequelize.getQueryInterface();
398
-
399
- yield queryInterface.dropTable(_this.model.tableName, options);
371
+ yield queryInterface.dropTable(_this.getTableNameWithSchema(), options);
400
372
  }
401
-
402
373
  _this.remove();
403
374
  })();
404
375
  }
405
-
406
376
  existsInDb(options) {
407
377
  var _this2 = this;
408
-
409
378
  return _asyncToGenerator(function* () {
410
- return _this2.db.collectionExistsInDb(_this2.name, options);
379
+ return _this2.db.queryInterface.collectionTableExists(_this2, options);
411
380
  })();
412
381
  }
413
-
414
382
  removeField(name) {
415
383
  if (!this.fields.has(name)) {
416
384
  return;
417
385
  }
418
-
419
386
  const field = this.fields.get(name);
420
387
  const bool = this.fields.delete(name);
421
-
422
388
  if (bool) {
423
389
  if (this.isParent()) {
424
- var _iterator5 = _createForOfIteratorHelper(this.db.inheritanceMap.getChildren(this.name, {
425
- deep: false
426
- })),
427
- _step5;
428
-
390
+ var _iterator7 = _createForOfIteratorHelper(this.db.inheritanceMap.getChildren(this.name, {
391
+ deep: false
392
+ })),
393
+ _step7;
429
394
  try {
430
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
431
- const child = _step5.value;
395
+ for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
396
+ const child = _step7.value;
432
397
  const childCollection = this.db.getCollection(child);
433
398
  const existField = childCollection.getField(name);
434
-
435
399
  if (existField && existField.options.inherit) {
436
400
  childCollection.removeField(name);
437
401
  }
438
402
  }
439
403
  } catch (err) {
440
- _iterator5.e(err);
404
+ _iterator7.e(err);
441
405
  } finally {
442
- _iterator5.f();
406
+ _iterator7.f();
443
407
  }
444
408
  }
445
-
446
409
  this.emit('field.afterRemove', field);
447
410
  }
448
-
449
411
  return field;
450
412
  }
451
413
  /**
452
414
  * TODO
453
415
  */
454
-
455
-
456
416
  updateOptions(options, mergeOptions) {
457
417
  let newOptions = _lodash().default.cloneDeep(options);
458
-
459
418
  newOptions = (0, _deepmerge().default)(this.options, newOptions, mergeOptions);
460
419
  this.context.database.emit('beforeUpdateCollection', this, newOptions);
461
420
  this.options = newOptions;
462
421
  this.setFields(options.fields, false);
463
- this.setRepository(options.repository);
422
+ if (options.repository) {
423
+ this.setRepository(options.repository);
424
+ }
464
425
  this.context.database.emit('afterUpdateCollection', this);
465
426
  return this;
466
427
  }
467
-
468
428
  setSortable(sortable) {
469
429
  if (!sortable) {
470
430
  return;
471
431
  }
472
-
473
432
  if (sortable === true) {
474
433
  this.setField('sort', {
475
434
  type: 'sort',
476
435
  hidden: true
477
436
  });
478
437
  }
479
-
480
438
  if (typeof sortable === 'string') {
481
439
  this.setField(sortable, {
482
440
  type: 'sort',
@@ -484,8 +442,7 @@ class Collection extends _events().EventEmitter {
484
442
  });
485
443
  } else if (typeof sortable === 'object') {
486
444
  const name = sortable.name,
487
- opts = _objectWithoutProperties(sortable, _excluded2);
488
-
445
+ opts = _objectWithoutProperties(sortable, _excluded2);
489
446
  this.setField(name || 'sort', _objectSpread({
490
447
  type: 'sort',
491
448
  hidden: true
@@ -498,30 +455,23 @@ class Collection extends _events().EventEmitter {
498
455
  * @param name
499
456
  * @param options
500
457
  */
501
-
502
-
503
458
  updateField(name, options) {
504
459
  if (!this.hasField(name)) {
505
460
  throw new Error(`field ${name} not exists`);
506
461
  }
507
-
508
462
  if (options.name && options.name !== name) {
509
463
  this.removeField(name);
510
464
  }
511
-
512
465
  this.setField(options.name || name, options);
513
466
  }
514
-
515
467
  addIndex(index) {
516
468
  if (!index) {
517
469
  return;
518
- } // collection defined indexes
519
-
520
-
470
+ }
471
+ // collection defined indexes
521
472
  let indexes = this.model.options.indexes || [];
522
473
  let indexName = [];
523
474
  let indexItem;
524
-
525
475
  if (typeof index === 'string') {
526
476
  indexItem = {
527
477
  fields: [index]
@@ -536,140 +486,146 @@ class Collection extends _events().EventEmitter {
536
486
  indexItem = index;
537
487
  indexName = index.fields;
538
488
  }
539
-
540
489
  if (_lodash().default.isEqual(this.model.primaryKeyAttributes, indexName)) {
541
490
  return;
542
491
  }
543
-
544
492
  const name = this.model.primaryKeyAttributes.join(',');
545
-
546
493
  if (name.startsWith(`${indexName.join(',')},`)) {
547
494
  return;
548
495
  }
549
-
550
- var _iterator6 = _createForOfIteratorHelper(indexes),
551
- _step6;
552
-
496
+ var _iterator8 = _createForOfIteratorHelper(indexes),
497
+ _step8;
553
498
  try {
554
- for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
555
- const item = _step6.value;
556
-
499
+ for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
500
+ const item = _step8.value;
557
501
  if (_lodash().default.isEqual(item.fields, indexName)) {
558
502
  return;
559
503
  }
560
-
561
504
  const name = item.fields.join(',');
562
-
563
505
  if (name.startsWith(`${indexName.join(',')},`)) {
564
506
  return;
565
507
  }
566
508
  }
567
509
  } catch (err) {
568
- _iterator6.e(err);
510
+ _iterator8.e(err);
569
511
  } finally {
570
- _iterator6.f();
512
+ _iterator8.f();
571
513
  }
572
-
573
514
  if (!indexItem) {
574
515
  return;
575
516
  }
576
-
577
517
  indexes.push(indexItem);
578
- const tableName = this.model.getTableName(); // @ts-ignore
579
-
580
- this.model._indexes = this.model.options.indexes // @ts-ignore
518
+ const tableName = this.model.getTableName();
519
+ // @ts-ignore
520
+ this.model._indexes = this.model.options.indexes
521
+ // @ts-ignore
581
522
  .map(index => _sequelize().Utils.nameIndex(this.model._conformIndex(index), tableName)).map(item => {
582
523
  if (item.name && item.name.length > 63) {
583
524
  item.name = 'i_' + (0, _utils.md5)(item.name);
584
525
  }
585
-
586
526
  return item;
587
527
  });
588
528
  this.refreshIndexes();
589
529
  }
590
-
591
530
  removeIndex(fields) {
592
531
  if (!fields) {
593
532
  return;
594
- } // @ts-ignore
595
-
596
-
597
- const indexes = this.model._indexes; // @ts-ignore
598
-
533
+ }
534
+ // @ts-ignore
535
+ const indexes = this.model._indexes;
536
+ // @ts-ignore
599
537
  this.model._indexes = indexes.filter(item => {
600
538
  return !_lodash().default.isEqual(item.fields, fields);
601
539
  });
602
540
  this.refreshIndexes();
603
541
  }
604
-
605
542
  refreshIndexes() {
606
543
  // @ts-ignore
607
- const indexes = this.model._indexes; // @ts-ignore
608
-
544
+ const indexes = this.model._indexes;
545
+ // @ts-ignore
609
546
  this.model._indexes = _lodash().default.uniqBy(indexes.filter(item => {
610
547
  return item.fields.every(field => Object.values(this.model.rawAttributes).find(fieldVal => fieldVal.field === field));
611
548
  }).map(item => {
612
549
  if (this.options.underscored) {
613
550
  item.fields = item.fields.map(field => (0, _utils.snakeCase)(field));
614
551
  }
615
-
616
552
  return item;
617
553
  }), 'name');
618
554
  }
619
-
620
555
  sync(syncOptions) {
621
556
  var _this3 = this;
622
-
623
557
  return _asyncToGenerator(function* () {
624
558
  const modelNames = new Set([_this3.model.name]);
625
559
  const associations = _this3.model.associations;
626
-
627
560
  for (const associationKey in associations) {
628
561
  const association = associations[associationKey];
629
562
  modelNames.add(association.target.name);
630
-
631
563
  if (association.through) {
632
564
  modelNames.add(association.through.model.name);
633
565
  }
634
566
  }
635
-
636
- const models = []; // @ts-ignore
637
-
567
+ const models = [];
568
+ // @ts-ignore
638
569
  _this3.context.database.sequelize.modelManager.forEachModel(model => {
639
570
  if (modelNames.has(model.name)) {
640
571
  models.push(model);
641
572
  }
642
573
  });
643
-
644
574
  for (var _i2 = 0, _models = models; _i2 < _models.length; _i2++) {
645
575
  const model = _models[_i2];
646
576
  yield model.sync(syncOptions);
647
577
  }
648
578
  })();
649
579
  }
650
-
651
580
  isInherited() {
652
581
  return false;
653
582
  }
654
-
655
583
  isParent() {
656
584
  return this.context.database.inheritanceMap.isParentNode(this.name);
657
585
  }
658
-
659
- addSchemaTableName() {
586
+ getTableNameWithSchema() {
660
587
  const tableName = this.model.tableName;
661
-
662
- if (this.options.schema) {
663
- return this.db.utils.addSchema(tableName, this.options.schema);
588
+ if (this.collectionSchema() && this.db.inDialect('postgres')) {
589
+ return this.db.utils.addSchema(tableName, this.collectionSchema());
590
+ }
591
+ return tableName;
592
+ }
593
+ tableNameAsString(options) {
594
+ const tableNameWithSchema = this.getTableNameWithSchema();
595
+ if (_lodash().default.isString(tableNameWithSchema)) {
596
+ return tableNameWithSchema;
597
+ }
598
+ const schema = tableNameWithSchema.schema;
599
+ const tableName = tableNameWithSchema.tableName;
600
+ if ((options === null || options === void 0 ? void 0 : options.ignorePublicSchema) && schema === 'public') {
601
+ return tableName;
602
+ }
603
+ return `${schema}.${tableName}`;
604
+ }
605
+ getTableNameWithSchemaAsString() {
606
+ const tableName = this.model.tableName;
607
+ if (this.collectionSchema() && this.db.inDialect('postgres')) {
608
+ return `${this.collectionSchema()}.${tableName}`;
664
609
  }
665
-
666
610
  return tableName;
667
611
  }
668
-
669
612
  quotedTableName() {
670
- return this.db.utils.quoteTable(this.addSchemaTableName());
613
+ return this.db.utils.quoteTable(this.getTableNameWithSchema());
614
+ }
615
+ collectionSchema() {
616
+ if (this.options.schema) {
617
+ return this.options.schema;
618
+ }
619
+ if (this.db.options.schema) {
620
+ return this.db.options.schema;
621
+ }
622
+ if (this.db.inDialect('postgres')) {
623
+ return 'public';
624
+ }
625
+ return undefined;
626
+ }
627
+ isView() {
628
+ return false;
671
629
  }
672
-
673
630
  }
674
-
675
631
  exports.Collection = Collection;