optimistic_locking.test.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. const Support = require('../support');
  3. const { DataTypes, OptimisticLockError } = require('@sequelize/core');
  4. const chai = require('chai');
  5. const expect = chai.expect;
  6. describe(Support.getTestDialectTeaser('Model'), () => {
  7. describe('optimistic locking', () => {
  8. let Account;
  9. beforeEach(async function () {
  10. Account = this.sequelize.define(
  11. 'Account',
  12. {
  13. number: {
  14. type: DataTypes.INTEGER,
  15. },
  16. },
  17. {
  18. version: true,
  19. },
  20. );
  21. await Account.sync({ force: true });
  22. });
  23. it('should increment the version on save', async () => {
  24. const account0 = await Account.create({ number: 1 });
  25. account0.number += 1;
  26. expect(account0.version).to.eq(0);
  27. const account = await account0.save();
  28. expect(account.version).to.eq(1);
  29. });
  30. it('should increment the version on update', async () => {
  31. const account1 = await Account.create({ number: 1 });
  32. expect(account1.version).to.eq(0);
  33. const account0 = await account1.update({ number: 2 });
  34. expect(account0.version).to.eq(1);
  35. account0.number += 1;
  36. const account = await account0.save();
  37. expect(account.number).to.eq(3);
  38. expect(account.version).to.eq(2);
  39. });
  40. it('prevents stale instances from being saved', async () => {
  41. await expect(
  42. (async () => {
  43. const accountA = await Account.create({ number: 1 });
  44. const accountB0 = await Account.findByPk(accountA.id);
  45. accountA.number += 1;
  46. await accountA.save();
  47. const accountB = await accountB0;
  48. accountB.number += 1;
  49. return await accountB.save();
  50. })(),
  51. ).to.eventually.be.rejectedWith(OptimisticLockError);
  52. });
  53. it('increment() also increments the version', async () => {
  54. const account1 = await Account.create({ number: 1 });
  55. expect(account1.version).to.eq(0);
  56. const account0 = await account1.increment('number', { by: 1 });
  57. const account = await account0.reload();
  58. expect(account.version).to.eq(1);
  59. });
  60. it('decrement() also increments the version', async () => {
  61. const account1 = await Account.create({ number: 1 });
  62. expect(account1.version).to.eq(0);
  63. const account0 = await account1.decrement('number', { by: 1 });
  64. const account = await account0.reload();
  65. expect(account.version).to.eq(1);
  66. });
  67. });
  68. });