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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@saga-bus/store-mysql

v0.2.1

Published

MySQL saga store for saga-bus

Readme

@saga-bus/store-mysql

MySQL / MariaDB saga store for saga-bus.

Installation

npm install @saga-bus/store-mysql mysql2
# or
pnpm add @saga-bus/store-mysql mysql2

Features

  • MySQL 5.7+: Native JSON column support
  • MariaDB 10.2+: Compatible with MariaDB
  • Cloud Databases: Works with PlanetScale, Vitess, AWS Aurora
  • Optimistic Concurrency: Version-based conflict detection
  • Connection Pooling: Built-in pool management
  • Query Helpers: Find, count, and cleanup methods

Quick Start

import { createBus } from "@saga-bus/core";
import { MySqlSagaStore } from "@saga-bus/store-mysql";

const store = new MySqlSagaStore({
  pool: {
    host: "localhost",
    user: "root",
    password: "password",
    database: "sagas",
  },
});

await store.initialize();

const bus = createBus({
  store,
  // ... other config
});

await bus.start();

Configuration

interface MySqlSagaStoreOptions {
  /** Connection pool or pool configuration */
  pool: Pool | PoolOptions;

  /** Table name for saga instances (default: "saga_instances") */
  tableName?: string;
}

Database Schema

Create the required table:

CREATE TABLE saga_instances (
  id             VARCHAR(128) NOT NULL,
  saga_name      VARCHAR(128) NOT NULL,
  correlation_id VARCHAR(256) NOT NULL,
  version        INT NOT NULL,
  is_completed   BOOLEAN NOT NULL DEFAULT FALSE,
  state          JSON NOT NULL,
  created_at     TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at     TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

  PRIMARY KEY (saga_name, id),
  UNIQUE KEY idx_correlation (saga_name, correlation_id),
  KEY idx_cleanup (saga_name, is_completed, updated_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Examples

Basic Usage

import { MySqlSagaStore } from "@saga-bus/store-mysql";

const store = new MySqlSagaStore({
  pool: {
    host: "localhost",
    user: "root",
    password: "password",
    database: "sagas",
  },
});

await store.initialize();

// Find by saga ID
const state = await store.getById("OrderSaga", "saga-123");

// Find by correlation ID
const stateByCorr = await store.getByCorrelationId("OrderSaga", "order-456");

// Insert new saga
await store.insert("OrderSaga", "order-789", {
  orderId: "order-789",
  status: "pending",
  metadata: {
    sagaId: "saga-new",
    version: 1,
    isCompleted: false,
    createdAt: new Date(),
    updatedAt: new Date(),
    archivedAt: null,
    timeoutMs: null,
    timeoutExpiresAt: null,
  },
});

// Update with concurrency check
await store.update("OrderSaga", updatedState, expectedVersion);

// Delete
await store.delete("OrderSaga", "saga-123");

With PlanetScale

const store = new MySqlSagaStore({
  pool: {
    host: "aws.connect.psdb.cloud",
    user: "your-username",
    password: "your-password",
    database: "your-database",
    ssl: { rejectUnauthorized: true },
  },
});

With Existing Connection Pool

import { createPool } from "mysql2/promise";

const pool = createPool({
  host: "localhost",
  user: "root",
  password: "password",
  database: "sagas",
  connectionLimit: 10,
});

const store = new MySqlSagaStore({
  pool, // Use existing pool
});

await store.initialize();

Query Helpers

// Find sagas by name with pagination
const sagas = await store.findByName("OrderSaga", {
  limit: 10,
  offset: 0,
  completed: false,
});

// Count sagas
const total = await store.countByName("OrderSaga");
const completed = await store.countByName("OrderSaga", { completed: true });

// Cleanup old completed sagas
const oneWeekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
const deleted = await store.deleteCompletedBefore("OrderSaga", oneWeekAgo);
console.log(`Deleted ${deleted} completed sagas`);

Optimistic Concurrency

The store uses version-based optimistic concurrency control:

// Read current state
const state = await store.getById("OrderSaga", "saga-123");
const expectedVersion = state.metadata.version;

// Make changes
state.status = "completed";
state.metadata.version += 1;
state.metadata.updatedAt = new Date();

try {
  // Update with version check
  await store.update("OrderSaga", state, expectedVersion);
} catch (error) {
  if (error instanceof ConcurrencyError) {
    // State was modified by another process
    // Reload and retry
  }
}

Error Handling

import { ConcurrencyError } from "@saga-bus/core";

try {
  await store.update("OrderSaga", state, expectedVersion);
} catch (error) {
  if (error instanceof ConcurrencyError) {
    console.log(`Concurrency conflict: expected v${error.expectedVersion}, actual v${error.actualVersion}`);
  }
}

Testing

For local development, you can run MySQL in Docker:

docker run -e MYSQL_ROOT_PASSWORD=password -e MYSQL_DATABASE=sagas \
  -p 3306:3306 --name mysql \
  mysql:8

Then create the table:

docker exec -it mysql mysql -uroot -ppassword sagas -e "
CREATE TABLE saga_instances (
  id VARCHAR(128) NOT NULL,
  saga_name VARCHAR(128) NOT NULL,
  correlation_id VARCHAR(256) NOT NULL,
  version INT NOT NULL,
  is_completed BOOLEAN NOT NULL DEFAULT FALSE,
  state JSON NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (saga_name, id),
  UNIQUE KEY idx_correlation (saga_name, correlation_id),
  KEY idx_cleanup (saga_name, is_completed, updated_at)
) ENGINE=InnoDB;
"

For unit tests, use an in-memory store:

import { InMemorySagaStore } from "@saga-bus/core";

const testStore = new InMemorySagaStore();

License

MIT