2.3 install knex / knex-migrate & initialize migration tables

wb todoMVC Master >> 2.3 install knex/knex-migarate & init…

Install & init knex

Open terminal and navigate to your project’s root folder

$ cd ~/Sites/swag/todo-api

Install knex globally so we can access the CLI

$ npm install knex -g

Install knex & postgres locally so the application is aware of it

$ npm install knex pg --save

Initialize knex

$ knex init

Configure knex

create a new folder called ‘/.knex’ in your project root

$ mkdir .knex

Open the knexfile.js located in project root

$ open ~/Sites/swag/todo-api/knexfile.js

Modify your knexfile.js with the appropriate connection configurations.

We also have to manually require & load the dotenv package otherwise kinex-migrate will not be able to populate the process.env variables.

Initialize migration scripts & verify valid dev db connection

Create a knex init_db migration which does nothing. It should fail if something is terribly wrong, like there is no database server to connect to.
(It should default to the development db connection. We’ll get into specifying different db connections from the command line later.)

$ knex migrate:make init_db --debug

Modify the generated file. We just created a boilerplate migration script. It will be named {timestamp}_init_db.js and it will be located in our migrations folder (/.knex/migrations). Open the file and modify like below. If the methods do not return a promise our migrations will generate a warning.

Let’s double check that there is nothing belligerently wrong with our setup by migrating our database to it’s latest release, which is still an empty database.

$ knex migrate:latest --debug

If everything worked as expected we should have an empty dev database with the exception of knex migration tables.

Start psql and connect to your database

$ psql -U todo_system -d todo_dev

List all tables

> \dt

It should look something like the below. (I’m using “medium” instead of “todo_dev” to write this tutorial)

Apply the same migration scripts to our test db & verify valid test db connection.

Let’s run the same migration on our todo_test database.

$ knex migrate:latest --debug --env test

Open your terminal that is connected to psql and connect to your test database.

> \c todo_test

Verify that the knex_migration tables were created successfully

\dt

Tutorial Navigation

The master tutorial doc is located here: WB todoMVC MASTER

Previous Step: 2.2 dotenv install & config with PSQL connect data

Next Step: 2.4 init knex-migrate & create Todo table via knex-migrate

Show your support

Clapping shows how much you appreciated Will Barnes’s story.