helpers.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. function checkNamingCollision(association) {
  3. if (Object.prototype.hasOwnProperty.call(association.source.rawAttributes, association.as)) {
  4. throw new Error(
  5. `Naming collision between attribute '${association.as}'` +
  6. ` and association '${association.as}' on model ${association.source.name}` +
  7. '. To remedy this, change either foreignKey or as in your association definition'
  8. );
  9. }
  10. }
  11. exports.checkNamingCollision = checkNamingCollision;
  12. function addForeignKeyConstraints(newAttribute, source, target, options, key) {
  13. // FK constraints are opt-in: users must either set `foreignKeyConstraints`
  14. // on the association, or request an `onDelete` or `onUpdate` behavior
  15. if (options.foreignKeyConstraint || options.onDelete || options.onUpdate) {
  16. // Find primary keys: composite keys not supported with this approach
  17. const primaryKeys = Object.keys(source.primaryKeys)
  18. .map(primaryKeyAttribute => source.rawAttributes[primaryKeyAttribute].field || primaryKeyAttribute);
  19. if (primaryKeys.length === 1 || !primaryKeys.includes(key)) {
  20. if (source._schema) {
  21. newAttribute.references = {
  22. model: source.sequelize.getQueryInterface().QueryGenerator.addSchema({
  23. tableName: source.tableName,
  24. _schema: source._schema,
  25. _schemaDelimiter: source._schemaDelimiter
  26. })
  27. };
  28. } else {
  29. newAttribute.references = { model: source.tableName };
  30. }
  31. newAttribute.references.key = key || primaryKeys[0];
  32. newAttribute.onDelete = options.onDelete;
  33. newAttribute.onUpdate = options.onUpdate;
  34. }
  35. }
  36. }
  37. exports.addForeignKeyConstraints = addForeignKeyConstraints;
  38. /**
  39. * Mixin (inject) association methods to model prototype
  40. *
  41. * @private
  42. *
  43. * @param {Object} association instance
  44. * @param {Object} obj Model prototype
  45. * @param {Array} methods Method names to inject
  46. * @param {Object} aliases Mapping between model and association method names
  47. *
  48. */
  49. function mixinMethods(association, obj, methods, aliases) {
  50. aliases = aliases || {};
  51. for (const method of methods) {
  52. // don't override custom methods
  53. if (!Object.prototype.hasOwnProperty.call(obj, association.accessors[method])) {
  54. const realMethod = aliases[method] || method;
  55. obj[association.accessors[method]] = function() {
  56. return association[realMethod](this, ...Array.from(arguments));
  57. };
  58. }
  59. }
  60. }
  61. exports.mixinMethods = mixinMethods;