destroy-all.test.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import type {
  2. CreationOptional,
  3. InferAttributes,
  4. InferCreationAttributes,
  5. NonAttribute,
  6. } from '@sequelize/core';
  7. import { DataTypes, Model } from '@sequelize/core';
  8. import { Attribute, BelongsTo, NotNull } from '@sequelize/core/decorators-legacy';
  9. import { expect } from 'chai';
  10. import { sequelize, setResetMode } from '../support';
  11. describe('Sequelize#destroyAll', () => {
  12. setResetMode('drop');
  13. it('deletes rows in the right order to avoid foreign key constraint violations', async () => {
  14. class A extends Model<InferAttributes<A>, InferCreationAttributes<A>> {
  15. declare id: CreationOptional<number>;
  16. @Attribute(DataTypes.INTEGER)
  17. @NotNull
  18. declare bId: number;
  19. @BelongsTo(() => B, {
  20. foreignKey: {
  21. name: 'bId',
  22. onDelete: 'NO ACTION',
  23. },
  24. })
  25. declare b?: NonAttribute<B>;
  26. }
  27. class B extends Model<InferAttributes<B>, InferCreationAttributes<B>> {
  28. declare id: CreationOptional<number>;
  29. @Attribute(DataTypes.INTEGER)
  30. @NotNull
  31. declare cId: number;
  32. @BelongsTo(() => C, {
  33. foreignKey: {
  34. name: 'cId',
  35. onDelete: 'NO ACTION',
  36. },
  37. })
  38. declare c?: NonAttribute<C>;
  39. }
  40. class C extends Model<InferAttributes<C>, InferCreationAttributes<C>> {
  41. declare id: CreationOptional<number>;
  42. }
  43. sequelize.addModels([A, C, B]);
  44. await sequelize.sync();
  45. const c = await C.create();
  46. const b = await B.create({ cId: c.id });
  47. await A.create({ bId: b.id });
  48. // drop both tables
  49. await sequelize.destroyAll();
  50. expect(await A.count()).to.eq(0);
  51. expect(await B.count()).to.eq(0);
  52. expect(await C.count()).to.eq(0);
  53. });
  54. });