@nocobase/database 0.9.4-alpha.1 → 0.10.0-alpha.2

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 (47) hide show
  1. package/lib/database.js +2 -1
  2. package/lib/eager-loading/eager-loading-tree.d.ts +4 -0
  3. package/lib/eager-loading/eager-loading-tree.js +79 -16
  4. package/lib/fields/belongs-to-field.d.ts +1 -1
  5. package/lib/fields/belongs-to-field.js +3 -2
  6. package/lib/fields/belongs-to-many-field.js +1 -1
  7. package/lib/fields/has-many-field.js +1 -1
  8. package/lib/fields/has-one-field.js +1 -1
  9. package/lib/filter-parser.js +15 -9
  10. package/lib/listeners/append-child-collection-name-after-repository-find.js +5 -1
  11. package/lib/options-parser.d.ts +1 -1
  12. package/lib/options-parser.js +15 -11
  13. package/lib/relation-repository/multiple-relation-repository.js +2 -1
  14. package/lib/relation-repository/single-relation-repository.js +2 -1
  15. package/lib/repository.d.ts +12 -0
  16. package/lib/repository.js +166 -66
  17. package/lib/update-associations.js +1 -1
  18. package/lib/view/field-type-map.d.ts +2 -0
  19. package/lib/view/field-type-map.js +2 -0
  20. package/lib/view/view-inference.js +52 -26
  21. package/lib/view-collection.js +0 -1
  22. package/package.json +4 -4
  23. package/src/__tests__/eager-loading/eager-loading-tree.test.ts +149 -0
  24. package/src/__tests__/field-options/sort-by.test.ts +3 -1
  25. package/src/__tests__/filter.test.ts +54 -0
  26. package/src/__tests__/inhertits/collection-inherits.test.ts +165 -0
  27. package/src/__tests__/repository/create.test.ts +129 -6
  28. package/src/__tests__/repository/find.test.ts +11 -0
  29. package/src/__tests__/repository.test.ts +24 -0
  30. package/src/__tests__/update-associations.test.ts +109 -1
  31. package/src/__tests__/view/view-inference.test.ts +1 -0
  32. package/src/database.ts +4 -1
  33. package/src/eager-loading/eager-loading-tree.ts +92 -17
  34. package/src/fields/belongs-to-field.ts +6 -4
  35. package/src/fields/belongs-to-many-field.ts +2 -1
  36. package/src/fields/has-many-field.ts +1 -1
  37. package/src/fields/has-one-field.ts +1 -1
  38. package/src/filter-parser.ts +17 -9
  39. package/src/listeners/append-child-collection-name-after-repository-find.ts +9 -5
  40. package/src/options-parser.ts +25 -19
  41. package/src/relation-repository/multiple-relation-repository.ts +1 -0
  42. package/src/relation-repository/single-relation-repository.ts +1 -0
  43. package/src/repository.ts +84 -0
  44. package/src/update-associations.ts +3 -0
  45. package/src/view/field-type-map.ts +2 -0
  46. package/src/view/view-inference.ts +75 -43
  47. package/src/view-collection.ts +0 -1
package/lib/repository.js CHANGED
@@ -31,10 +31,14 @@ var _hasoneRepository = require("./relation-repository/hasone-repository");
31
31
  var _updateAssociations = require("./update-associations");
32
32
  var _updateGuard = require("./update-guard");
33
33
  var _eagerLoadingTree = require("./eager-loading/eager-loading-tree");
34
+ function _flat() {
35
+ const data = require("flat");
36
+ _flat = function _flat() {
37
+ return data;
38
+ };
39
+ return data;
40
+ }
34
41
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
35
- 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(_e) { throw _e; }, 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(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
36
- 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); }
37
- 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; }
38
42
  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; }
39
43
  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; }
40
44
  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; }
@@ -42,6 +46,9 @@ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typ
42
46
  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); }
43
47
  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); } }
44
48
  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); }); }; }
49
+ 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(_e) { throw _e; }, 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(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
50
+ 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); }
51
+ 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; }
45
52
  var __decorate = void 0 && (void 0).__decorate || function (decorators, target, key, desc) {
46
53
  var c = arguments.length,
47
54
  r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
@@ -97,6 +104,51 @@ class Repository {
97
104
  this.collection = collection;
98
105
  this.model = collection.model;
99
106
  }
107
+ static valuesToFilter(values, filterKeys) {
108
+ const filterAnd = [];
109
+ const flattedValues = (0, _flat().flatten)(values);
110
+ const keyWithOutArrayIndex = key => {
111
+ const chunks = key.split('.');
112
+ return chunks.filter(chunk => {
113
+ return !Boolean(chunk.match(/\d+/));
114
+ }).join('.');
115
+ };
116
+ var _iterator = _createForOfIteratorHelper(filterKeys),
117
+ _step;
118
+ try {
119
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
120
+ const filterKey = _step.value;
121
+ let filterValue;
122
+ for (var _i = 0, _Object$keys = Object.keys(flattedValues); _i < _Object$keys.length; _i++) {
123
+ const flattedKey = _Object$keys[_i];
124
+ const flattedKeyWithoutIndex = keyWithOutArrayIndex(flattedKey);
125
+ if (flattedKeyWithoutIndex === filterKey) {
126
+ if (filterValue) {
127
+ if (Array.isArray(filterValue)) {
128
+ filterValue.push(flattedValues[flattedKey]);
129
+ } else {
130
+ filterValue = [filterValue, flattedValues[flattedKey]];
131
+ }
132
+ } else {
133
+ filterValue = flattedValues[flattedKey];
134
+ }
135
+ }
136
+ }
137
+ if (filterValue) {
138
+ filterAnd.push({
139
+ [filterKey]: filterValue
140
+ });
141
+ }
142
+ }
143
+ } catch (err) {
144
+ _iterator.e(err);
145
+ } finally {
146
+ _iterator.f();
147
+ }
148
+ return {
149
+ $and: filterAnd
150
+ };
151
+ }
100
152
  /**
101
153
  * return count by filter
102
154
  */
@@ -207,7 +259,8 @@ class Repository {
207
259
  model,
208
260
  rootAttributes: opts.attributes,
209
261
  includeOption: opts.include,
210
- rootOrder: opts.order
262
+ rootOrder: opts.order,
263
+ db: _this3.database
211
264
  });
212
265
  yield eagerLoadingTree.load(ids.map(i => i.pk), transaction);
213
266
  rows = eagerLoadingTree.root.instances;
@@ -262,6 +315,53 @@ class Repository {
262
315
  return rows.length == 1 ? rows[0] : null;
263
316
  })();
264
317
  }
318
+ /**
319
+ * Get the first record matching the attributes or create it.
320
+ */
321
+ firstOrCreate(options) {
322
+ var _this6 = this;
323
+ return _asyncToGenerator(function* () {
324
+ const filterKeys = options.filterKeys,
325
+ values = options.values,
326
+ transaction = options.transaction;
327
+ const filter = Repository.valuesToFilter(values, filterKeys);
328
+ const instance = yield _this6.findOne({
329
+ filter,
330
+ transaction
331
+ });
332
+ if (instance) {
333
+ return instance;
334
+ }
335
+ return _this6.create({
336
+ values,
337
+ transaction
338
+ });
339
+ })();
340
+ }
341
+ updateOrCreate(options) {
342
+ var _this7 = this;
343
+ return _asyncToGenerator(function* () {
344
+ const filterKeys = options.filterKeys,
345
+ values = options.values,
346
+ transaction = options.transaction;
347
+ const filter = Repository.valuesToFilter(values, filterKeys);
348
+ const instance = yield _this7.findOne({
349
+ filter,
350
+ transaction
351
+ });
352
+ if (instance) {
353
+ return yield _this7.update({
354
+ filterByTk: instance.get(_this7.collection.model.primaryKeyAttribute),
355
+ values,
356
+ transaction
357
+ });
358
+ }
359
+ return _this7.create({
360
+ values,
361
+ transaction
362
+ });
363
+ })();
364
+ }
265
365
  /**
266
366
  * Save instance to database
267
367
  *
@@ -269,20 +369,20 @@ class Repository {
269
369
  * @param options
270
370
  */
271
371
  create(options) {
272
- var _this6 = this;
372
+ var _this8 = this;
273
373
  return _asyncToGenerator(function* () {
274
374
  if (Array.isArray(options.values)) {
275
- return _this6.createMany(_objectSpread(_objectSpread({}, options), {}, {
375
+ return _this8.createMany(_objectSpread(_objectSpread({}, options), {}, {
276
376
  records: options.values
277
377
  }));
278
378
  }
279
- const transaction = yield _this6.getTransaction(options);
280
- const guard = _updateGuard.UpdateGuard.fromOptions(_this6.model, _objectSpread(_objectSpread({}, options), {}, {
379
+ const transaction = yield _this8.getTransaction(options);
380
+ const guard = _updateGuard.UpdateGuard.fromOptions(_this8.model, _objectSpread(_objectSpread({}, options), {}, {
281
381
  action: 'create',
282
- underscored: _this6.collection.options.underscored
382
+ underscored: _this8.collection.options.underscored
283
383
  }));
284
384
  const values = guard.sanitize(options.values || {});
285
- const instance = yield _this6.model.create(values, _objectSpread(_objectSpread({}, options), {}, {
385
+ const instance = yield _this8.model.create(values, _objectSpread(_objectSpread({}, options), {}, {
286
386
  transaction
287
387
  }));
288
388
  if (!instance) {
@@ -292,10 +392,10 @@ class Repository {
292
392
  transaction
293
393
  }));
294
394
  if (options.hooks !== false) {
295
- yield _this6.database.emitAsync(`${_this6.collection.name}.afterCreateWithAssociations`, instance, _objectSpread(_objectSpread({}, options), {}, {
395
+ yield _this8.database.emitAsync(`${_this8.collection.name}.afterCreateWithAssociations`, instance, _objectSpread(_objectSpread({}, options), {}, {
296
396
  transaction
297
397
  }));
298
- yield _this6.database.emitAsync(`${_this6.collection.name}.afterSaveWithAssociations`, instance, _objectSpread(_objectSpread({}, options), {}, {
398
+ yield _this8.database.emitAsync(`${_this8.collection.name}.afterSaveWithAssociations`, instance, _objectSpread(_objectSpread({}, options), {}, {
299
399
  transaction
300
400
  }));
301
401
  instance.clearChangedWithAssociations();
@@ -310,26 +410,26 @@ class Repository {
310
410
  * @param options
311
411
  */
312
412
  createMany(options) {
313
- var _this7 = this;
413
+ var _this9 = this;
314
414
  return _asyncToGenerator(function* () {
315
- const transaction = yield _this7.getTransaction(options);
415
+ const transaction = yield _this9.getTransaction(options);
316
416
  const records = options.records;
317
417
  const instances = [];
318
- var _iterator = _createForOfIteratorHelper(records),
319
- _step;
418
+ var _iterator2 = _createForOfIteratorHelper(records),
419
+ _step2;
320
420
  try {
321
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
322
- const values = _step.value;
323
- const instance = yield _this7.create({
421
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
422
+ const values = _step2.value;
423
+ const instance = yield _this9.create({
324
424
  values,
325
425
  transaction
326
426
  });
327
427
  instances.push(instance);
328
428
  }
329
429
  } catch (err) {
330
- _iterator.e(err);
430
+ _iterator2.e(err);
331
431
  } finally {
332
- _iterator.f();
432
+ _iterator2.f();
333
433
  }
334
434
  return instances;
335
435
  })();
@@ -341,76 +441,76 @@ class Repository {
341
441
  * @param options
342
442
  */
343
443
  update(options) {
344
- var _this8 = this;
444
+ var _this10 = this;
345
445
  return _asyncToGenerator(function* () {
346
446
  if (Array.isArray(options.values)) {
347
- return _this8.updateMany(_objectSpread(_objectSpread({}, options), {}, {
447
+ return _this10.updateMany(_objectSpread(_objectSpread({}, options), {}, {
348
448
  records: options.values
349
449
  }));
350
450
  }
351
- const transaction = yield _this8.getTransaction(options);
352
- const guard = _updateGuard.UpdateGuard.fromOptions(_this8.model, _objectSpread(_objectSpread({}, options), {}, {
353
- underscored: _this8.collection.options.underscored
451
+ const transaction = yield _this10.getTransaction(options);
452
+ const guard = _updateGuard.UpdateGuard.fromOptions(_this10.model, _objectSpread(_objectSpread({}, options), {}, {
453
+ underscored: _this10.collection.options.underscored
354
454
  }));
355
455
  const values = guard.sanitize(options.values);
356
- const queryOptions = _this8.buildQueryOptions(options);
357
- const instances = yield _this8.find(_objectSpread(_objectSpread({}, queryOptions), {}, {
456
+ const queryOptions = _this10.buildQueryOptions(options);
457
+ const instances = yield _this10.find(_objectSpread(_objectSpread({}, queryOptions), {}, {
358
458
  transaction
359
459
  }));
360
- var _iterator2 = _createForOfIteratorHelper(instances),
361
- _step2;
460
+ var _iterator3 = _createForOfIteratorHelper(instances),
461
+ _step3;
362
462
  try {
363
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
364
- const instance = _step2.value;
463
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
464
+ const instance = _step3.value;
365
465
  yield (0, _updateAssociations.updateModelByValues)(instance, values, _objectSpread(_objectSpread({}, options), {}, {
366
466
  sanitized: true,
367
467
  transaction
368
468
  }));
369
469
  }
370
470
  } catch (err) {
371
- _iterator2.e(err);
471
+ _iterator3.e(err);
372
472
  } finally {
373
- _iterator2.f();
473
+ _iterator3.f();
374
474
  }
375
475
  if (options.hooks !== false) {
376
- var _iterator3 = _createForOfIteratorHelper(instances),
377
- _step3;
476
+ var _iterator4 = _createForOfIteratorHelper(instances),
477
+ _step4;
378
478
  try {
379
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
380
- const instance = _step3.value;
381
- yield _this8.database.emitAsync(`${_this8.collection.name}.afterUpdateWithAssociations`, instance, _objectSpread(_objectSpread({}, options), {}, {
479
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
480
+ const instance = _step4.value;
481
+ yield _this10.database.emitAsync(`${_this10.collection.name}.afterUpdateWithAssociations`, instance, _objectSpread(_objectSpread({}, options), {}, {
382
482
  transaction
383
483
  }));
384
- yield _this8.database.emitAsync(`${_this8.collection.name}.afterSaveWithAssociations`, instance, _objectSpread(_objectSpread({}, options), {}, {
484
+ yield _this10.database.emitAsync(`${_this10.collection.name}.afterSaveWithAssociations`, instance, _objectSpread(_objectSpread({}, options), {}, {
385
485
  transaction
386
486
  }));
387
487
  instance.clearChangedWithAssociations();
388
488
  }
389
489
  } catch (err) {
390
- _iterator3.e(err);
490
+ _iterator4.e(err);
391
491
  } finally {
392
- _iterator3.f();
492
+ _iterator4.f();
393
493
  }
394
494
  }
395
495
  return instances;
396
496
  })();
397
497
  }
398
498
  updateMany(options) {
399
- var _this9 = this;
499
+ var _this11 = this;
400
500
  return _asyncToGenerator(function* () {
401
- const transaction = yield _this9.getTransaction(options);
501
+ const transaction = yield _this11.getTransaction(options);
402
502
  const records = options.records;
403
503
  const instances = [];
404
- var _iterator4 = _createForOfIteratorHelper(records),
405
- _step4;
504
+ var _iterator5 = _createForOfIteratorHelper(records),
505
+ _step5;
406
506
  try {
407
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
408
- const values = _step4.value;
409
- const filterByTk = values[_this9.model.primaryKeyAttribute];
507
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
508
+ const values = _step5.value;
509
+ const filterByTk = values[_this11.model.primaryKeyAttribute];
410
510
  if (!filterByTk) {
411
511
  throw new Error('filterByTk invalid');
412
512
  }
413
- const instance = yield _this9.update({
513
+ const instance = yield _this11.update({
414
514
  values,
415
515
  filterByTk,
416
516
  transaction
@@ -418,32 +518,32 @@ class Repository {
418
518
  instances.push(instance);
419
519
  }
420
520
  } catch (err) {
421
- _iterator4.e(err);
521
+ _iterator5.e(err);
422
522
  } finally {
423
- _iterator4.f();
523
+ _iterator5.f();
424
524
  }
425
525
  return instances;
426
526
  })();
427
527
  }
428
528
  destroy(options) {
429
- var _this10 = this;
529
+ var _this12 = this;
430
530
  return _asyncToGenerator(function* () {
431
- const transaction = yield _this10.getTransaction(options);
432
- const modelFilterKey = _this10.collection.filterTargetKey;
531
+ const transaction = yield _this12.getTransaction(options);
532
+ const modelFilterKey = _this12.collection.filterTargetKey;
433
533
  options = options;
434
534
  if (options['individualHooks'] === undefined) {
435
535
  options['individualHooks'] = true;
436
536
  }
437
537
  const filterByTk = options.filterByTk && !_lodash().default.isArray(options.filterByTk) ? [options.filterByTk] : options.filterByTk;
438
- if (_this10.collection.model.primaryKeyAttributes.length !== 1 && filterByTk && !_lodash().default.get(_this10.collection.options, 'filterTargetKey')) {
439
- if (_this10.collection.model.primaryKeyAttributes.length > 1) {
538
+ if (_this12.collection.model.primaryKeyAttributes.length !== 1 && filterByTk && !_lodash().default.get(_this12.collection.options, 'filterTargetKey')) {
539
+ if (_this12.collection.model.primaryKeyAttributes.length > 1) {
440
540
  throw new Error(`filterByTk is not supported for composite primary key`);
441
541
  } else {
442
542
  throw new Error(`filterByTk is not supported for collection that has no primary key`);
443
543
  }
444
544
  }
445
545
  if (filterByTk && !options.filter) {
446
- return yield _this10.model.destroy(_objectSpread(_objectSpread({}, options), {}, {
546
+ return yield _this12.model.destroy(_objectSpread(_objectSpread({}, options), {}, {
447
547
  where: {
448
548
  [modelFilterKey]: {
449
549
  [_sequelize().Op.in]: filterByTk
@@ -453,26 +553,26 @@ class Repository {
453
553
  }));
454
554
  }
455
555
  if (options.filter) {
456
- if (_this10.collection.model.primaryKeyAttributes.length !== 1 && !_lodash().default.get(_this10.collection.options, 'filterTargetKey')) {
457
- const queryOptions = _objectSpread({}, _this10.buildQueryOptions(options));
458
- return yield _this10.model.destroy(_objectSpread(_objectSpread({}, queryOptions), {}, {
556
+ if (_this12.collection.model.primaryKeyAttributes.length !== 1 && !_lodash().default.get(_this12.collection.options, 'filterTargetKey')) {
557
+ const queryOptions = _objectSpread({}, _this12.buildQueryOptions(options));
558
+ return yield _this12.model.destroy(_objectSpread(_objectSpread({}, queryOptions), {}, {
459
559
  transaction
460
560
  }));
461
561
  }
462
- let pks = (yield _this10.find({
562
+ let pks = (yield _this12.find({
463
563
  filter: options.filter,
464
564
  transaction
465
565
  })).map(instance => instance.get(modelFilterKey));
466
566
  if (filterByTk) {
467
567
  pks = _lodash().default.intersection(pks.map(i => `${i}`), filterByTk.map(i => `${i}`));
468
568
  }
469
- return yield _this10.destroy(_objectSpread(_objectSpread({}, _lodash().default.omit(options, 'filter')), {}, {
569
+ return yield _this12.destroy(_objectSpread(_objectSpread({}, _lodash().default.omit(options, 'filter')), {}, {
470
570
  filterByTk: pks,
471
571
  transaction
472
572
  }));
473
573
  }
474
574
  if (options.truncate) {
475
- return yield _this10.model.destroy(_objectSpread(_objectSpread({}, options), {}, {
575
+ return yield _this12.model.destroy(_objectSpread(_objectSpread({}, options), {}, {
476
576
  truncate: true,
477
577
  transaction
478
578
  }));
@@ -505,13 +605,13 @@ class Repository {
505
605
  return parser.toSequelizeParams();
506
606
  }
507
607
  getTransaction(options, autoGen = false) {
508
- var _this11 = this;
608
+ var _this13 = this;
509
609
  return _asyncToGenerator(function* () {
510
610
  if (_lodash().default.isPlainObject(options) && options.transaction) {
511
611
  return options.transaction;
512
612
  }
513
613
  if (autoGen) {
514
- return yield _this11.model.sequelize.transaction();
614
+ return yield _this13.model.sequelize.transaction();
515
615
  }
516
616
  return null;
517
617
  })();
@@ -196,7 +196,7 @@ function isReverseAssociationPair(a, b) {
196
196
  if (typeSet.has('HasOne') && typeSet.has('BelongsTo') || typeSet.has('HasMany') && typeSet.has('BelongsTo')) {
197
197
  const sourceAssoc = a.associationType == 'BelongsTo' ? b : a;
198
198
  const targetAssoc = sourceAssoc == a ? b : a;
199
- return sourceAssoc.source.name === targetAssoc.target.name && sourceAssoc.foreignKey === targetAssoc.foreignKey && sourceAssoc.sourceKey === targetAssoc.targetKey;
199
+ return sourceAssoc.source.name === targetAssoc.target.name && sourceAssoc.target.name === targetAssoc.source.name && sourceAssoc.foreignKey === targetAssoc.foreignKey && sourceAssoc.sourceKey === targetAssoc.targetKey;
200
200
  }
201
201
  return false;
202
202
  }
@@ -4,6 +4,8 @@ declare const _default: {
4
4
  varchar: string;
5
5
  text: string;
6
6
  char: string;
7
+ oid: string;
8
+ name: string;
7
9
  smallint: string;
8
10
  integer: string;
9
11
  bigint: string;
@@ -9,6 +9,8 @@ const postgres = {
9
9
  varchar: 'string',
10
10
  text: 'text',
11
11
  char: 'string',
12
+ oid: 'string',
13
+ name: 'string',
12
14
  smallint: 'integer',
13
15
  integer: 'integer',
14
16
  bigint: 'bigInt',
@@ -13,11 +13,12 @@ function _mathjs() {
13
13
  return data;
14
14
  }
15
15
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16
- 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; }
17
- 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; }
18
- 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; }
19
- function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
20
- 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); }
16
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
17
+ 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."); }
18
+ 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); }
19
+ 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; }
20
+ 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; } }
21
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
21
22
  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); } }
22
23
  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); }); }; }
23
24
  class ViewFieldInference {
@@ -33,38 +34,63 @@ class ViewFieldInference {
33
34
  viewName: options.viewName,
34
35
  schema: options.viewSchema
35
36
  });
36
- // @ts-ignore
37
- return Object.fromEntries(Object.entries(columns).map(([name, column]) => {
37
+ const rawFields = [];
38
+ for (var _i = 0, _Object$entries = Object.entries(columns); _i < _Object$entries.length; _i++) {
39
+ const _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
40
+ name = _Object$entries$_i[0],
41
+ column = _Object$entries$_i[1];
42
+ const inferResult = {
43
+ name
44
+ };
38
45
  const usage = columnUsage[name];
39
46
  if (usage) {
47
+ const collection = db.tableNameCollectionMap.get(`${usage.table_schema ? `${usage.table_schema}.` : ''}${usage.table_name}`);
40
48
  const collectionField = (() => {
41
- const tableName = `${usage.table_schema ? `${usage.table_schema}.` : ''}${usage.table_name}`;
42
- const collection = db.tableNameCollectionMap.get(tableName);
43
49
  if (!collection) return false;
44
- const fieldValue = Object.values(collection.model.rawAttributes).find(field => field.field === usage.column_name);
45
- if (!fieldValue) {
50
+ const fieldAttribute = Object.values(collection.model.rawAttributes).find(field => field.field === usage.column_name);
51
+ if (!fieldAttribute) {
46
52
  return false;
47
53
  }
48
54
  // @ts-ignore
49
- const fieldName = fieldValue === null || fieldValue === void 0 ? void 0 : fieldValue.fieldName;
55
+ const fieldName = fieldAttribute.fieldName;
50
56
  return collection.getField(fieldName);
51
57
  })();
52
- if (collectionField && collectionField.options.interface) {
53
- return [name, {
54
- name,
55
- type: collectionField.type,
56
- source: `${collectionField.collection.name}.${collectionField.name}`
57
- }];
58
+ const belongsToAssociationField = (() => {
59
+ if (!collection) return false;
60
+ const field = Object.values(collection.model.rawAttributes).find(field => field.field === usage.column_name);
61
+ if (!field) {
62
+ return false;
63
+ }
64
+ const association = Object.values(collection.model.associations).find(association => association.associationType === 'BelongsTo' && association.foreignKey === field.fieldName);
65
+ if (!association) {
66
+ return false;
67
+ }
68
+ return collection.getField(association.as);
69
+ })();
70
+ if (belongsToAssociationField) {
71
+ rawFields.push([belongsToAssociationField.name, {
72
+ name: belongsToAssociationField.name,
73
+ type: belongsToAssociationField.type,
74
+ source: `${belongsToAssociationField.collection.name}.${belongsToAssociationField.name}`
75
+ }]);
76
+ }
77
+ if (collectionField) {
78
+ if (collectionField.options.interface) {
79
+ inferResult.type = collectionField.type;
80
+ inferResult.source = `${collectionField.collection.name}.${collectionField.name}`;
81
+ }
58
82
  }
59
83
  }
60
- return [name, _objectSpread({
61
- name
62
- }, _this.inferToFieldType({
63
- db,
64
- name,
65
- type: column.type
66
- }))];
67
- }));
84
+ if (!inferResult.type) {
85
+ Object.assign(inferResult, _this.inferToFieldType({
86
+ db,
87
+ name,
88
+ type: column.type
89
+ }));
90
+ }
91
+ rawFields.push([name, inferResult]);
92
+ }
93
+ return Object.fromEntries(rawFields);
68
94
  })();
69
95
  }
70
96
  static inferToFieldType(options) {
@@ -9,7 +9,6 @@ class ViewCollection extends _collection.Collection {
9
9
  constructor(options, context) {
10
10
  options.autoGenId = false;
11
11
  options.timestamps = false;
12
- options.underscored = false;
13
12
  super(options, context);
14
13
  }
15
14
  sequelizeModelOptions() {
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@nocobase/database",
3
- "version": "0.9.4-alpha.1",
3
+ "version": "0.10.0-alpha.2",
4
4
  "description": "",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./lib/index.d.ts",
7
7
  "license": "Apache-2.0",
8
8
  "dependencies": {
9
- "@nocobase/logger": "0.9.4-alpha.1",
10
- "@nocobase/utils": "0.9.4-alpha.1",
9
+ "@nocobase/logger": "0.10.0-alpha.2",
10
+ "@nocobase/utils": "0.10.0-alpha.2",
11
11
  "async-mutex": "^0.3.2",
12
12
  "cron-parser": "4.4.0",
13
13
  "deepmerge": "^4.2.2",
@@ -28,5 +28,5 @@
28
28
  "url": "git+https://github.com/nocobase/nocobase.git",
29
29
  "directory": "packages/database"
30
30
  },
31
- "gitHead": "0b4936be557be918dbdf8196dadcbc7eb395906d"
31
+ "gitHead": "85028ae1733fcbd46ecd5d291dacbdc175f7f073"
32
32
  }