Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
107 lines (83 sloc) 2.07 KB

Knex

https://knexjs.org/

CLI

yarn run knex migrate:make $NAME
yarn run knex migrate:latest
yarn run knex migrate:rollback

Convenience Scripts

Update your package.json:

{% code-tabs %} {% code-tabs-item title="package.json" %}

{
  "scripts": {
    "latest": "yarn run knex migrate:latest",
    "rollback": "yarn run knex migrate:rollback"
  },
}

{% endcode-tabs-item %} {% endcode-tabs %}

Migrations

Naming

yarn run knex migrate:make $verb_table

Examples:

yarn run knex migrate:make createTable_users
yarn run knex migrate:make alterTable_users_add_createdBy

Sticks to the knex function names createTable and alterTable

Avoid an "init" file.

{% hint style="warning" %} Avoid an "init" file.

For example, do not have a: 20190424135724_init.js

Instead just do: 20190424135724_create_entries.js

This explains what the file does. {% endhint %}

  • Tables should be plural
  • Fields should be in camelCase

Also see Engineering Code > Naming

Promises:

{% code-tabs %} {% code-tabs-item title="20190424104046_createTable_users.js" %}

exports.up = function(knex, Promise) {
  return knex.schema
    .createTable('users', table => {
      table
        .uuid('uuid')
        .primary();
      table
        .datetime('createdAt')
        .defaultTo(knex.fn.now())
        .index();
      table
        .datetime('updatedAt')
        .defaultTo(knex.fn.now())
        .index();
      table
        .string('name')
        .collate('utf8mb4_unicode_ci')
        .defaultTo('')
        .notNullable();
      table
        .string('email')
        .collate('utf8mb4_unicode_ci')
        .unique()
        .defaultTo('')
        .notNullable();
    })
};

exports.down = function(knex, Promise) {
  return knex.schema
    .dropTable('users');
};

{% endcode-tabs-item %} {% endcode-tabs %}

You can’t perform that action at this time.