MySQL Memory Server

1.14.1 · active · verified Wed Apr 22

mysql-memory-server is a JavaScript/TypeScript library designed to spin up ephemeral MySQL databases programmatically, primarily for testing, continuous integration, and local development. It automatically downloads the necessary MySQL binaries from MySQL's CDN if a specified version is not already installed on the system, supporting a wide range of MySQL versions from 5.7.19 up to 9.6.0. The package supports Linux, macOS, and Windows environments, including Alpine Linux. It is actively maintained with frequent releases, often introducing support for the latest MySQL versions and fixing platform-specific issues. The current stable version is 1.14.1. Key differentiators include its ability to manage multiple concurrent database instances, automatic shutdown upon process exit, and robust cross-platform compatibility.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to spin up an ephemeral MySQL instance, connect to it using `mysql2/promise`, run a simple query, and then properly shut down the database. Requires `mysql2` as a separate dependency.

import { createDB } from 'mysql-memory-server';
import sql from 'mysql2/promise'; // Remember to `npm install mysql2`

async function runEphemeralMySQL() {
  // Create a new database with default options, or specify a version
  const db = await createDB({
    version: '8.4.x' // Example: specify a MySQL 8.4 version
  });

  console.log(`MySQL server started on port: ${db.port}, database: ${db.dbName}`);

  // Connect to the new database
  const connection = await sql.createConnection({
    host: '127.0.0.1',
    user: db.username,
    port: db.port,
    database: db.dbName,
    password: '' // Default password is an empty string
  });

  try {
    // Run your queries here
    const [rows] = await connection.execute('SELECT 1 + 1 AS solution');
    console.log('Query result:', rows);

    await connection.execute('CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(255))');
    console.log('Table "users" created.');

  } finally {
    // Once done, disconnect from the database
    await connection.end();
    console.log('Database connection closed.');

    // Then stop the database instance
    await db.stop();
    console.log('MySQL server stopped.');
  }
}

runEphemeralMySQL().catch(console.error);

view raw JSON →