npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mysql-transactional-tests

v1.0.3

Published

Wraps each test in transaction for mysql database (driver `mysql` and `mysql2`)

Downloads

8

Readme

MySQL Transactional tests

Actions Status Coverage

This library patches drivers mysql and mysql2 to allow implementation of transactional tests as it's done in Ruby on Rails, Laravel and Spring.

The main purpose of this library is to make each of your tests run in a separate transaction, rollback after each test, so every change you're making in database disappears.

This allows to focus on testing logic without thinking about clearing database, and it's performed much faster than clearing tables with DELETE/TRUNCATE.

The library allows developers to write easy and fast tests which communicates with real database instead of writing tons of mocks and stubs in tests for queries to database. Besides you can persist seeds for database only once before start all tests and then don't think about recreation of state in database after each executed test.

Library supported:

Install

npm i mysql-transactional-tests -S;

# you had install one of this driver:
npm i mysql -S;
npm i mysql2 -S;

Example

You should import library before import your client for database. If you use database client or ORM which is based on mysql driver then you should import mysql-transactional-tests/mysql otherwise mysql-transactional-tests/mysql2 for mysql2 driver.

// As early as possible import library (mysql driver)
import { startTransaction, unPatch } from 'mysql-transactional-tests/mysql';
// As early as possible import library (mysql2 driver)
// import { startTransaction, unPatch } from 'mysql-transactional-tests/mysql2';

import MySQLClient from '../client/mysql_client';
const mysqlConfig = require('../mysql.config.json');

const dbName = mysqlConfig.database;
const mysqlClient = new MySQLClient(mysqlConfig);

describe('[mysql]: transaction per test', () => {
  let rollback: () => Promise<void>;

  beforeEach(async () => {
    // Start transaction before each test
    ({ rollback } = await startTransaction());
  });

  afterEach(async () => {
    // Rollback transaction after each test
    await rollback();
  });

  afterAll(async () => {
    // Close connection to db and unpatche driver
    mysqlClient.close();
    unPatch();
  });

  // simple query
  it('insert', async () => {
    await mysqlClient.query(
      `INSERT INTO ${dbName}.employee SET first_name='John', last_name='Brown', age=35, sex='man', income=23405`,
    );
    const result = await mysqlClient.query(`SELECT * FROM ${dbName}.employee`);
    expect(result).toHaveLength(4);
  });

  // query in transaction
  it('insert: commit', async () => {
    const trx = await mysqlClient.beginTransaction();
    await trx.query(
      `INSERT INTO ${dbName}.employee SET first_name='John', last_name='Brown', age=35, sex='man', income=23405`,
    );
    await trx.commit();
    const result = await mysqlClient.query(`SELECT * FROM ${dbName}.employee`);
    expect(result).toHaveLength(4);
  });
});

More examples with many library

How it works

Every test which performs a query is wrapped into a transaction:

it('insert', async () => {
  await mysqlClient.query(
    `INSERT INTO ${dbName}.employee SET first_name='John', last_name='Brown', age=35, sex='man', income=23405`,
  );
  const result = await mysqlClient.query(`SELECT * FROM ${dbName}.employee`);
  expect(result).toHaveLength(4);
});

Will be producing next SQL:

-- global transaction was started
BEGIN;
  INSERT INTO employee SET first_name='John', last_name='Brown', age=35, sex='man', income=23405;
  SELECT * FROM employee;
-- global transaction was finished
ROLLBACK;

Transactions in your code will be converted to savepoints. Operator BEGIN/START TRANSACTION will be replaced to SAVEPOINT, COMMIT to RELEASE SAVEPOINT, ROLLBACK to ROLLBACK TO SAVEPOINT.

it('insert: commit', async () => {
  const trx = await mysqlClient.beginTransaction();
  await trx.query(
    `INSERT INTO ${dbName}.employee SET first_name='John', last_name='Brown', age=35, sex='man', income=23405`,
  );
  await trx.commit();
  const result = await mysqlClient.query(`SELECT * FROM ${dbName}.employee`);
  expect(result).toHaveLength(4);
});

Will be producing next SQL:

-- global transaction was started
BEGIN;
  SAVEPOINT sp_1;
  INSERT INTO employee SET first_name='John', last_name='Brown', age=35, sex='man', income=23405;
  RELEASE SAVEPOINT sp_1;
  SELECT * FROM employee;
-- global transaction was finished
ROLLBACK;

Restrictions and Corner cases

The library doesn't allow to run test with parallel transactions because the library creates one connection (with transaction) for all queries.

it('insert: two parallel transcations: one commit, one rollback', async () => {
  const [ trx1, trx2 ] = await Promise.all([
    mysqlClient.beginTransaction(),
    mysqlClient.beginTransaction(),
  ]);

  await trx1.query(
    `INSERT INTO ${dbName}.employee SET first_name='John', last_name='Brown', age=35, sex='man', income=23405`,
  );
  await trx2.query(
    `INSERT INTO ${dbName}.employee SET first_name='Matthew', last_name='Black', age=45, sex='woman', income=11000`,
  );

  // Maybe generate error ❌
  await Promise.all([
    trx1.commit,
    trx2.rollback,
  ]);
});

This is because the order of commit/rollback of the transactions are not guaranteed when they are executed in parallel. Usually, it's not important for real transactions. Since the library transforms transactions in savepoints, the order release/rollback is very significant.

For example:

-- global transaction was started
BEGIN;

  SAVEPOINT sp_1;
  INSERT INTO employee SET first_name='John', last_name='Brown', age=35, sex='man', income=23405;
  SAVEPOINT sp_2;
  INSERT INTO employee SET first_name='Matthew', last_name='Black', age=45, sex='woman', income=11000;

  -- ✅
  RELEASE SAVEPOINT sp_2;
  RELEASE SAVEPOINT sp_1;

  -- ❌
  RELEASE SAVEPOINT sp_1;
  -- Not found savepoint sp_2
  RELEASE SAVEPOINT sp_2;

-- global transaction was finished
ROLLBACK;

Based on the above, you can use this library with tests which sequenctly open/close transactions (inside tested code) or with parallel transaction which are opened/closed based on principle LIFO (last in, first out):

it('insert: two parallel transcation, one commit, one rollback', async () => {
  // start two parallel transaction
  const trx1 = await mysqlClient.beginTransaction();
  const trx2 = await mysqlClient.beginTransaction();

  await trx1.query(
    `INSERT INTO ${dbName}.employee SET first_name='John', last_name='Brown', age=35, sex='man', income=23405`,
  );
  await trx2.query(
    `INSERT INTO ${dbName}.employee SET first_name='Matthew', last_name='Black', age=45, sex='woman', income=11000`,
  );

  // ✅
  await trx2.rollback();
  await trx1.commit();

  // ❌
  await trx1.commit();
  await trx2.rollback();

  const result = await mysqlClient.query(`SELECT * FROM ${dbName}.employee`);
  expect(result).toHaveLength(4);

  const notFound = await mysqlClient.query(`SELECT * FROM ${dbName}.employee WHERE first_name='Matthew' LIMIT 1`);
  expect(notFound).toHaveLength(0);
});

Debug and Isolation Level

Debug mode can be enabled with method setDebug:

import { setDebug } from 'mysql-transactional-tests/mysql';
// import { setDebug } from 'mysql-transactional-tests/mysql2';

setDebug(true);

You can set isolation level for transaction:

beforeEach(async () => {
  // Start transaction before each test
  ({ rollback } = await startTransaction({ isolationLevel: 'READ UNCOMMITTED' }));
});