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

auto-mysql-umzug

v0.0.8

Published

Small wrapper to integrate umzug as easy as possible in your app

Downloads

19

Readme

auto-mysql-umzug

This lib is a small wrapper around the migration lib umzug. It's intention is to integrate umzug as easily as possible into a node backend. The main use case is to provide an easy way to perform necessary database migrations automatically on startup of a node backend.

Installation

Install it like this:

npm install --save auto-msyql-umzug

Basic usage

In your node backend application, call the execute method on startup and only after the method's returned promise is resolved, continue starting up your application.

The execute method will return a Promise. It resolves into an array indicating if any migration had to be executed. So the possible resolutions of the returned Promise are:

  • resolved: Array of umzug.Migration ... database has not been up to date, at least one migration was actually executed
  • resolved: Empty array ... database has already been up to date, no migration executed
  • rejected: ... an error occurred

Usage example:

// before starting the app, perform database migration steps, if any
const migrate = require('auto-mysql-umzug')({
    dbName: DB_DATABASE,
    dbUser: DB_USER,
    dbPass: DB_PASSWORD
  });
  
// migrate db if it is not up to date
migrate.execute()
  .then((executedMigrations) => {
    if (executedMigrations.length) {
      console.log('migration was successful');
    } else {
      console.log('no migration necessary');
    }

    startApp(); // at this point - after successful migration - start your application
  })
  .catch(err => {
    console.log(`error at migration: ${err}`);

    // don't start application
    process.exit(1);
  });

Configuration

You can pass a config object to the lib. It must contain the database credentials (dbName, dbUser, dbPass and optional additional options).

The possible options are:

| Option | Type | Default | Required | Description | |---|---|---|---|---| | dbName | string | | ✔ | Name of the database | | dbUser | string | | ✔ | Username of the database user. User must have the necessary privileges to alter the database. For instance, the user must be allowed to create the migrations metadata table - and every migration you will create. | | dbPass | string | | ✔ | Password of the database user | | dbOptions | object | | ❌ | An object containing additional database options. These options are passed through to Sequelize backend, so all options which are understood by Sequelize's options property for the constructor are possible (see here). | | migrationDir | string | "migrations" | ❌ | Folder containing the migration files associated with the software version (see umzug for details on migration files). It can be an absolute or relative path. In case of a relative path, it will be resolved relative to the application's main folder (path.dirname(require.main.filename)). set the name of the directory which contains the migration files. Default is migrations. | | migrationTable | string | "_migrations" | ❌ | Name of the table which stores the executed migrations. Default is _migrations. | | filePattern | RegExp | /\.js$/ | ❌ | Regular expression to search for migration files in migrationDir | | logging | function\|boolean | | ❌ | Function that logs its arguments. It is called like the inbuilt function console.log. If true, uses console.log, otherwise nothing will be logged |

API after initialization

The initialization function returns an object with the functions execute, needsUpdate, needsDowngrade, and the initialized umzug library itself as umzug

execute

Definition
execute(options?: object): Promise<umzug.Migration[]>
Parameters

| Parameter | Type | Default | Required | Description | |---|---|---|---|---| | options.ignoreMissingMigrations | boolean | false | ❌ | If true, the function needsDowngrade is not called and therefore it is not checked, if there are missing but already executed migration files |

Returns

A promise that resolves into an array of the executed umzug.Migration, or an empty array if none were executed. If options.ignoreMissingMigrations is false and there are some missing migration files, then a rejected Promise is returned with a string stating that problem and it contains the filenames of the missing migration files.

Description

Checks for any possible downgrades with the function needsDowngrade and then executes any possible migrations with umzug.up().

needsUpdate

Definition
needsUpdate(): Promise<umzug.Migration[]>
Returns

A promise that resolves into an array of the pending umzug.Migration, or an empty array if none are pending

Description

This is just a wrapper for umzug.pending().

needsDowngrade

Definition
needsDowngrade(): Promise<umzug.Migration[]>
Returns

A promise that resolves into an array of the missing but already executed umzug.Migration, or an empty array if no executed migration is missing

Description

This function retrieves all executed migrations and checks if they also exist on disk. Usually when there is at least one missing, a version downgrade of your application happened, as the newer migrations are not included in the earlier application version.

umzug

This is the umzug library on its own. The main intention is to enable an easier downgrade module that is specific to your application. So you don't need to initialize umzug separately, making this wrapper nearly useless.

Migration files

The migrations folder (default: folder migrations/) contains the migration files. Each migration file is a Javascript file which ideally contains an up and a down method, which represent a function which achieves the task and a function that reverts a task. See umzug:migration files:format for details.

Note that the migration files are executed in the order of their filenames (sorted alphabetically). So, make sure that you either use a fixed-length numeric prefix or a timestamp (in a specific format).

When missing migrations are detected, all missing migrations are executed in the alphabetic order of their filenames.

Examples of migration file filenames are:

001-create-user-table.js
002-add-some-columns.js
003-other-things.js

or:

2019-05-10_153731-create-user-table.js
2019-05-12_164004-add-some-columns.js
2019-05-13_081445-other-things.js

Whatever you choose, be sure to stick to your chosen nomenclature consistently to ensure that the sort order is as intended.

The arguments to the migration methods (up() and down()) are configured in this lib using Umzug's migrations.params property. All properties listed under migrations.params are passed to the migration files' methods. In this case, each migration method will be called with two parameters:

  • query ... Sequelize's query object (which is what Sequelize.getQueryInterface() returns), see Sequelize/QueryInterface for the API
  • DataTypes ... Sequelize's constructor, see Sequelize/DataTypes for a description of Sequelize's data types

Mysql driver

Since the used Sequelize driver for using the mysql database relies on mysql2 as mysql lib, you should use mysql2 as a Mysql module for your application too. In most cases, this should not really be a problem because mysql2 is mostly compatible to mysql.