set-session-variables.test.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { QueryTypes } from '@sequelize/core';
  2. import { expect } from 'chai';
  3. import {
  4. createSingleTransactionalTestSequelizeInstance,
  5. getTestDialect,
  6. sequelize,
  7. setResetMode,
  8. } from '../support';
  9. const dialectName = getTestDialect();
  10. describe('sequelize.setSessionVariables', () => {
  11. if (!['mysql', 'mariadb'].includes(dialectName)) {
  12. return;
  13. }
  14. setResetMode('none');
  15. it(`rejects if no connection or transaction is provided`, async () => {
  16. await expect(sequelize.setSessionVariables({ foo: 'bar' })).to.be.rejectedWith(
  17. Error,
  18. 'specify either options.transaction or options.connection',
  19. );
  20. });
  21. it('supports CLS transactions', async () => {
  22. const clsSequelize = await createSingleTransactionalTestSequelizeInstance(sequelize, {
  23. disableClsTransactions: false,
  24. });
  25. await clsSequelize.transaction(async () => {
  26. await clsSequelize.setSessionVariables({ foo: 'bar' });
  27. const [data] = await clsSequelize.query<{ foo: string }>('SELECT @foo as `foo`', {
  28. type: QueryTypes.SELECT,
  29. });
  30. expect(data).to.be.ok;
  31. expect(data.foo).to.equal('bar');
  32. });
  33. });
  34. it('supports manual transactions', async () => {
  35. const transaction = await sequelize.startUnmanagedTransaction();
  36. try {
  37. await sequelize.setSessionVariables({ foo: 'bar' }, { transaction });
  38. const [data] = await sequelize.query<{ foo: string }>('SELECT @foo as `foo`', {
  39. type: QueryTypes.SELECT,
  40. transaction,
  41. });
  42. expect(data).to.be.ok;
  43. expect(data.foo).to.equal('bar');
  44. await transaction.commit();
  45. } catch (error) {
  46. await transaction.rollback();
  47. throw error;
  48. }
  49. });
  50. it('supports connections', async () => {
  51. await sequelize.withConnection(async connection => {
  52. await sequelize.setSessionVariables({ foo: 'bar' }, { connection });
  53. const [data] = await sequelize.query<{ foo: string }>('SELECT @foo as `foo`', {
  54. type: QueryTypes.SELECT,
  55. connection,
  56. });
  57. expect(data).to.be.ok;
  58. expect(data.foo).to.equal('bar');
  59. });
  60. });
  61. it('supports setting multiple values', async () => {
  62. await sequelize.withConnection(async connection => {
  63. await sequelize.setSessionVariables({ foo: 'bar', foos: 'bars' }, { connection });
  64. const [data] = await sequelize.query<{ foo: string; foos: string }>(
  65. 'SELECT @foo as `foo`, @foos as `foos`',
  66. { type: QueryTypes.SELECT, connection },
  67. );
  68. expect(data).to.be.ok;
  69. expect(data.foo).to.equal('bar');
  70. expect(data.foos).to.equal('bars');
  71. });
  72. });
  73. });