knex-migrate-sql-file
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

knex-migrate-sql-file

Use sql files instead of (or in addition to) knex.schema methods.

Exports getMigrators, upSQL and downSQL functions which executes knex.raw() method on SQL files having same file name appended .up.sql and .down.sql.

Usage

Add one of the below scripts to the package.json based on your usage (with TypeScript ESM support):

{
  "scripts": {
    "knex": "NODE_OPTIONS='--experimental-vm-modules --loader ts-node/esm' dotenv knex",
    "knex:sqlmigration": "NODE_OPTIONS='--experimental-vm-modules --loader ts-node/esm' sqlmigration"
  }
}

Alternative 1: Generate Files

  • Execute generator. It creates migration file and SQL files. Created files are dependency free. (They are are not dependent to this library.)
$ npm run knex:sqlmigration add-user-table

Alternative 2: Export from Migration File

  • Create knex migration file.
  • Create SQL files.
  • Export functions of this library from migration file.
$ npm run knex migrate:make add-user-table

/db/migrations/20180516163212_add-user-table.js

import getMigrators from "knex-migrate-sql-file";

export const { up, down } = getMigrators();

/db/migrations/20180516163212_add-user-table.up.sql

CREATE TABLE "user" (...);

/db/migrations/20180516163212_add-user-table.down.sql

DROP TABLE "user";

Alternative 3: Use Functions

  • Create knex migration file.
  • Create SQL files.
  • Use functions of this library in the migration file.
$ npm run knex migrate:make add-user-table

/db/migrations/20180516163212_add-user-table.js

import { upSQL, downSQL } from "knex-migrate-sql-file";
 
export async function up(knex: Knex): Promise<void> {
  await upSQL(knex);
}

export async function down(knex: Knex): Promise<void> {
  await downSQL(knex);
}

/db/migrations/20180516163212_add-user-table.up.sql

CREATE TABLE "user" (...);

/db/migrations/20180516163212_add-user-table.down.sql

DROP TABLE "user";

Package Sidebar

Install

npm i knex-migrate-sql-file

Weekly Downloads

503

Version

2.0.0

License

MIT

Unpacked Size

16.6 kB

Total Files

16

Last publish

Collaborators

  • ozum