@htc-class/simple-migrations
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

Simple Migrations

A barebones MySQL migration runner, that only works with @htc-class/simple-mysql

Installation

npm install @htc-class/simple-migrations

Setting up Migrations

You must create a folder in your project directory with the path ./src/migrations. Then, in that folder, start adding migration files, like the one shown below:

// ./src/migrations/01_CreateUserTable.ts
import { Migration } from '@htc-class/simple-migrations';
import SimpleSQL from '@htc-class/simple-mysql';

export default class CreateUserTable implements Migration {
  async up(db: SimpleSQL): Promise<void> {
    await db.mutate(/* sql */ `
      CREATE TABLE users (
        name TEXT NOT NULL,
        age INT NOT NULL,
        has_beard BOOLEAN NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      );
    `);
  }

  async down(db: SimpleSQL): Promise<void> {
    await db.mutate(/* sql */ `DROP TABLE users;`);
  }
}

The migrations will be ordered by the alphabetical filesystem order, so it's recommended to prefix your filenames with a number or date, to keep them in order, like this:

./src/
  migrations/
    _db-provider.ts
    01_CreateUserTable.ts
    02_CreateCardsTable.ts
    03_AddUserForeignKey.ts
    ...etc...

Creating the Database Provider

In the ./src/migrations/ folder, you also must provide a file named exactly _db-provider.ts that exports a single function which provides an authenticated DB instance. Here's a template:

// ./src/migrations/_db-provider.ts
import { DbProvider } from '@htc-class/simple-migrations';
import SimpleMySQL from '@htc-class/simple-mysql';

const dbProvider: DbProvider = () => {
  // or, import a configured instance from another file (if you have one)
  // and just export that, to avoid duplication
  return new SimpleMySQL({
    database: process.env.DATABASE_NAME ?? ``,
    user: process.env.DATABASE_USER ?? ``,
    password: process.env.DATABASE_PASSWORD ?? ``,
  });
};

export default dbProvider;

Running Migrations

The library exposes an npm binary called simple-migrate, allowing for 5 commands, as shown here:

npx simple-migrate up:all   # run all pending migrations "up"
npx simple-migrate up:one   # run ONE pending migration "up"
npx simple-migrate down:all # run all pending migrations "down"
npx simple-migrate down:one # run ONE pending migration "down"
npx simple-migrate reset    # same as running `down:all` and then `up:all`

Readme

Keywords

none

Package Sidebar

Install

npm i @htc-class/simple-migrations

Weekly Downloads

3

Version

1.0.1

License

MIT

Unpacked Size

17.7 kB

Total Files

12

Last publish

Collaborators

  • jaredhenderson