has-many-mixins.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. import type {
  2. CreationOptional,
  3. HasManyAddAssociationsMixin,
  4. HasManyHasAssociationsMixin,
  5. HasManyRemoveAssociationsMixin,
  6. HasManySetAssociationsMixin,
  7. InferAttributes,
  8. InferCreationAttributes,
  9. } from '@sequelize/core';
  10. import { DataTypes, Model } from '@sequelize/core';
  11. import { AllowNull, Attribute, HasMany, NotNull } from '@sequelize/core/decorators-legacy';
  12. import { expect } from 'chai';
  13. import {
  14. beforeAll2,
  15. createMultiTransactionalTestSequelizeInstance,
  16. sequelize,
  17. setResetMode,
  18. } from '../support';
  19. const dialect = sequelize.dialect;
  20. describe('hasMany Mixins', () => {
  21. setResetMode('destroy');
  22. const vars = beforeAll2(async () => {
  23. class Article extends Model<InferAttributes<Article>, InferCreationAttributes<Article>> {
  24. declare id: CreationOptional<number>;
  25. @HasMany(() => Label, 'articleId')
  26. declare labels?: Label[];
  27. declare setLabels: HasManySetAssociationsMixin<Label, Label['id']>;
  28. declare removeLabels: HasManyRemoveAssociationsMixin<Label, Label['id']>;
  29. declare hasLabels: HasManyHasAssociationsMixin<Label, Label['id']>;
  30. declare addLabels: HasManyAddAssociationsMixin<Label, Label['id']>;
  31. @HasMany(() => NonNullLabel, 'articleId')
  32. declare nonNullLabels?: NonNullLabel[];
  33. declare setNonNullLabels: HasManySetAssociationsMixin<NonNullLabel, NonNullLabel['id']>;
  34. declare removeNonNullLabels: HasManyRemoveAssociationsMixin<NonNullLabel, NonNullLabel['id']>;
  35. }
  36. class Label extends Model<InferAttributes<Label>, InferCreationAttributes<Label>> {
  37. declare id: CreationOptional<number>;
  38. @AllowNull
  39. @Attribute(DataTypes.INTEGER)
  40. declare articleId: number | null;
  41. }
  42. class NonNullLabel extends Model<
  43. InferAttributes<NonNullLabel>,
  44. InferCreationAttributes<NonNullLabel>
  45. > {
  46. declare id: CreationOptional<number>;
  47. @NotNull
  48. @Attribute(DataTypes.INTEGER)
  49. declare articleId: number;
  50. }
  51. sequelize.addModels([Article, Label, NonNullLabel]);
  52. await sequelize.sync({ force: true });
  53. return { Article, Label, NonNullLabel };
  54. });
  55. describe('setAssociations', () => {
  56. it('associates target models to the source model', async () => {
  57. const { Label, Article } = vars;
  58. const [article, label] = await Promise.all([Article.create(), Label.create()]);
  59. // TODO: this should be null - https://github.com/sequelize/sequelize/issues/14671
  60. expect(label.articleId).to.beNullish();
  61. await article.setLabels([label]);
  62. await label.reload();
  63. expect(label.articleId).to.equal(article.id);
  64. });
  65. it('supports any iterable', async () => {
  66. const { Label, Article } = vars;
  67. const [article, label] = await Promise.all([Article.create(), Label.create()]);
  68. // TODO: this should be null - https://github.com/sequelize/sequelize/issues/14671
  69. expect(label.articleId).to.beNullish();
  70. await article.setLabels(new Set([label]));
  71. await label.reload();
  72. expect(label.articleId).to.equal(article.id);
  73. });
  74. it('unlinks the previous associations', async () => {
  75. const { Label, Article } = vars;
  76. const article = await Article.create();
  77. const label1 = await Label.create({ articleId: article.id });
  78. const label2 = await Label.create();
  79. expect(label1.articleId).to.equal(article.id);
  80. // TODO: this should be null - https://github.com/sequelize/sequelize/issues/14671
  81. expect(label2.articleId).to.beNullish();
  82. await article.setLabels([label2]);
  83. await Promise.all([label1.reload(), label2.reload()]);
  84. expect(label1.articleId).to.equal(null);
  85. expect(label2.articleId).to.equal(article.id);
  86. });
  87. it('clears associations when the parameter is null', async () => {
  88. const { Label, Article } = vars;
  89. const article = await Article.create();
  90. const label = await Label.create({ articleId: article.id });
  91. expect(label.articleId).to.equal(article.id);
  92. await article.setLabels(null);
  93. await label.reload();
  94. expect(label.articleId).to.equal(null);
  95. });
  96. it('destroys the previous associations if `destroyPrevious` is true', async () => {
  97. const { Label, Article } = vars;
  98. const article = await Article.create();
  99. await Label.create({ articleId: article.id });
  100. await article.setLabels(null, { destroyPrevious: true });
  101. expect(await Label.count()).to.equal(0);
  102. });
  103. it('destroys the previous associations if the foreign key is not nullable', async () => {
  104. const { NonNullLabel, Article } = vars;
  105. const article = await Article.create();
  106. await NonNullLabel.create({ articleId: article.id });
  107. await article.setNonNullLabels(null);
  108. expect(await NonNullLabel.count()).to.equal(0);
  109. });
  110. it('supports passing the primary key instead of an object', async () => {
  111. const { Label, Article } = vars;
  112. const [article, label] = await Promise.all([Article.create(), Label.create()]);
  113. await article.setLabels([label.id]);
  114. await label.reload();
  115. expect(label.articleId).to.equal(article.id);
  116. });
  117. });
  118. describe('addAssociations', () => {
  119. it('associates target models to the source model', async () => {
  120. const { Label, Article } = vars;
  121. const [article, label] = await Promise.all([Article.create(), Label.create()]);
  122. // TODO: this should be null - https://github.com/sequelize/sequelize/issues/14671
  123. expect(label.articleId).to.beNullish();
  124. await article.addLabels([label]);
  125. await label.reload();
  126. expect(label.articleId).to.equal(article.id);
  127. });
  128. it('supports any iterable', async () => {
  129. const { Label, Article } = vars;
  130. const [article, label] = await Promise.all([Article.create(), Label.create()]);
  131. // TODO: this should be null - https://github.com/sequelize/sequelize/issues/14671
  132. expect(label.articleId).to.beNullish();
  133. await article.addLabels(new Set([label]));
  134. await label.reload();
  135. expect(label.articleId).to.equal(article.id);
  136. });
  137. it('supports passing the primary key instead of an object', async () => {
  138. const { Label, Article } = vars;
  139. const [article, label] = await Promise.all([Article.create(), Label.create()]);
  140. // TODO: this should be null - https://github.com/sequelize/sequelize/issues/14671
  141. expect(label.articleId).to.beNullish();
  142. await article.addLabels([label.id]);
  143. await label.reload();
  144. expect(label.articleId).to.equal(article.id);
  145. });
  146. });
  147. describe('removeAssociations', () => {
  148. it('unlinks the target models from the source model', async () => {
  149. const { Label, Article } = vars;
  150. const article = await Article.create();
  151. const label = await Label.create({ articleId: article.id });
  152. expect(label.articleId).to.equal(article.id);
  153. await article.removeLabels([label]);
  154. await label.reload();
  155. expect(label.articleId).to.equal(null);
  156. });
  157. it('supports any iterable', async () => {
  158. const { Label, Article } = vars;
  159. const article = await Article.create();
  160. const label = await Label.create({ articleId: article.id });
  161. expect(label.articleId).to.equal(article.id);
  162. await article.removeLabels(new Set([label]));
  163. await label.reload();
  164. expect(label.articleId).to.equal(null);
  165. });
  166. it('supports passing the primary key instead of an object', async () => {
  167. const { Label, Article } = vars;
  168. const article = await Article.create();
  169. const label = await Label.create({ articleId: article.id });
  170. expect(label.articleId).to.equal(article.id);
  171. await article.removeLabels([label.id]);
  172. await label.reload();
  173. expect(label.articleId).to.equal(null);
  174. });
  175. it('destroys the target models if `destroy` is true', async () => {
  176. const { Label, Article } = vars;
  177. const article = await Article.create();
  178. const label = await Label.create({ articleId: article.id });
  179. expect(label.articleId).to.equal(article.id);
  180. await article.removeLabels([label], { destroy: true });
  181. expect(await Label.count()).to.equal(0);
  182. });
  183. it('destroys the target models if the foreign key is not nullable', async () => {
  184. const { NonNullLabel, Article } = vars;
  185. const article = await Article.create();
  186. const label = await NonNullLabel.create({ articleId: article.id });
  187. expect(label.articleId).to.equal(article.id);
  188. await article.removeNonNullLabels([label]);
  189. expect(await NonNullLabel.count()).to.equal(0);
  190. });
  191. });
  192. describe('hasAssociations', () => {
  193. it('returns true if the target model is associated to the source model', async () => {
  194. const { Label, Article } = vars;
  195. const article = await Article.create();
  196. const label = await Label.create({ articleId: article.id });
  197. expect(await article.hasLabels([label])).to.equal(true);
  198. });
  199. it('supports any iterable', async () => {
  200. const { Label, Article } = vars;
  201. const article = await Article.create();
  202. const label = await Label.create({ articleId: article.id });
  203. expect(await article.hasLabels(new Set([label]))).to.equal(true);
  204. });
  205. it('supports passing the primary key instead of an object', async () => {
  206. const { Label, Article } = vars;
  207. const article = await Article.create();
  208. const label = await Label.create({ articleId: article.id });
  209. expect(await article.hasLabels([label.id])).to.equal(true);
  210. });
  211. });
  212. });
  213. describe('hasMany Mixins + transaction', () => {
  214. if (!dialect.supports.transactions) {
  215. return;
  216. }
  217. setResetMode('destroy');
  218. const vars = beforeAll2(async () => {
  219. class Article extends Model<InferAttributes<Article>, InferCreationAttributes<Article>> {
  220. declare id: CreationOptional<number>;
  221. @HasMany(() => Label, 'articleId')
  222. declare labels?: Label[];
  223. declare setLabels: HasManySetAssociationsMixin<Label, Label['id']>;
  224. declare removeLabels: HasManyRemoveAssociationsMixin<Label, Label['id']>;
  225. }
  226. class Label extends Model<InferAttributes<Label>, InferCreationAttributes<Label>> {
  227. declare id: CreationOptional<number>;
  228. @AllowNull
  229. @Attribute(DataTypes.INTEGER)
  230. declare articleId: number | null;
  231. }
  232. const transactionSequelize = await createMultiTransactionalTestSequelizeInstance(sequelize);
  233. transactionSequelize.addModels([Article, Label]);
  234. await transactionSequelize.sync({ force: true });
  235. return { Article, Label, transactionSequelize };
  236. });
  237. after(async () => {
  238. return vars.transactionSequelize.close();
  239. });
  240. describe('setAssociations', () => {
  241. it('supports transactions', async () => {
  242. const { Label, Article, transactionSequelize } = vars;
  243. const [article, label] = await Promise.all([Article.create(), Label.create()]);
  244. await transactionSequelize.transaction(async transaction => {
  245. await article.setLabels([label], { transaction });
  246. const labels0 = await Label.findAll({
  247. where: { articleId: article.id },
  248. transaction: null,
  249. });
  250. expect(labels0.length).to.equal(0);
  251. const labels = await Label.findAll({ where: { articleId: article.id }, transaction });
  252. expect(labels.length).to.equal(1);
  253. });
  254. });
  255. it('uses the transaction when destroying the previous associations', async () => {
  256. const { Label, Article, transactionSequelize } = vars;
  257. const [article, t] = await Promise.all([
  258. Article.create(),
  259. transactionSequelize.startUnmanagedTransaction(),
  260. ]);
  261. try {
  262. await Label.create({ articleId: article.id });
  263. await article.setLabels(null, { destroyPrevious: true, transaction: t });
  264. expect(await Label.count({ transaction: null })).to.equal(1);
  265. expect(await Label.count({ transaction: t })).to.equal(0);
  266. } finally {
  267. await t.rollback();
  268. }
  269. });
  270. it('uses the transaction when unsetting the previous associations', async () => {
  271. const { Label, Article, transactionSequelize } = vars;
  272. const [article, t] = await Promise.all([
  273. Article.create(),
  274. transactionSequelize.startUnmanagedTransaction(),
  275. ]);
  276. try {
  277. await Label.create({ articleId: article.id });
  278. await article.setLabels(null, { transaction: t });
  279. expect(
  280. (await Label.findOne({ rejectOnEmpty: true, transaction: null })).articleId,
  281. ).to.equal(article.id);
  282. expect((await Label.findOne({ rejectOnEmpty: true, transaction: t })).articleId).to.equal(
  283. null,
  284. );
  285. } finally {
  286. await t.rollback();
  287. }
  288. });
  289. });
  290. describe('removeAssociations', () => {
  291. it('uses the transaction when updating the foreign key', async () => {
  292. const { Label, Article, transactionSequelize } = vars;
  293. const [article, t] = await Promise.all([
  294. Article.create(),
  295. transactionSequelize.startUnmanagedTransaction(),
  296. ]);
  297. try {
  298. const label = await Label.create({ articleId: article.id });
  299. await article.removeLabels([label], { transaction: t });
  300. expect(
  301. (await Label.findOne({ rejectOnEmpty: true, transaction: null })).articleId,
  302. ).to.equal(article.id);
  303. expect((await Label.findOne({ rejectOnEmpty: true, transaction: t })).articleId).to.equal(
  304. null,
  305. );
  306. } finally {
  307. await t.rollback();
  308. }
  309. });
  310. it('uses the transaction when deleting the target models', async () => {
  311. const { Label, Article, transactionSequelize } = vars;
  312. const [article, t] = await Promise.all([
  313. Article.create(),
  314. transactionSequelize.startUnmanagedTransaction(),
  315. ]);
  316. try {
  317. const label = await Label.create({ articleId: article.id });
  318. await article.removeLabels([label], { destroy: true, transaction: t });
  319. expect(await Label.count({ transaction: null })).to.equal(1);
  320. expect(await Label.count({ transaction: t })).to.equal(0);
  321. } finally {
  322. await t.rollback();
  323. }
  324. });
  325. });
  326. });