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:

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

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.

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.

  • Tables should be plural

  • Fields should be in camelCase

Also see Engineering Code > Naming

Promises:

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');
};