Knex

CLI

1
yarn run knex migrate:make $NAME
2
yarn run knex migrate:latest
3
yarn run knex migrate:rollback
Copied!

Convenience Scripts

Update your package.json:
package.json
1
{
2
"scripts": {
3
"latest": "yarn run knex migrate:latest",
4
"rollback": "yarn run knex migrate:rollback"
5
},
6
}
Copied!

Migrations

Naming

1
yarn run knex migrate:make $verb_table
Copied!
Examples:
1
yarn run knex migrate:make createTable_users
2
yarn run knex migrate:make alterTable_users_add_createdBy
Copied!
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

Promises:

20190424104046_createTable_users.js
1
exports.up = function(knex, Promise) {
2
return knex.schema
3
.createTable('users', table => {
4
table
5
.uuid('uuid')
6
.primary();
7
table
8
.datetime('createdAt')
9
.defaultTo(knex.fn.now())
10
.index();
11
table
12
.datetime('updatedAt')
13
.defaultTo(knex.fn.now())
14
.index();
15
table
16
.string('name')
17
.collate('utf8mb4_unicode_ci')
18
.defaultTo('')
19
.notNullable();
20
table
21
.string('email')
22
.collate('utf8mb4_unicode_ci')
23
.unique()
24
.defaultTo('')
25
.notNullable();
26
})
27
};
28
29
exports.down = function(knex, Promise) {
30
return knex.schema
31
.dropTable('users');
32
};
Copied!
Last modified 2yr ago