Note:
<example>
is meant to denote text replaced by you (including brackets).
// global dependencies
npm install -g knex
// project's dependencies
npm install knex pg --save
// project's dev dependencies
npm nodemon --save-dev
$ psql
CREATE DATABASE <example>;
CREATE DATABASE <example_test>;
$ knex init
Created ./knexfile.js
Replace contents of ./knexfile.js
with:
module.exports = {
development: {
client: 'pg',
connection:'postgres://localhost/<examples>',
migrations: {
directory: './db/migrations'
},
seeds: {
directory: './db/seeds/dev'
},
useNullAsDefault: true
},
test: {
client: 'pg',
connection:'postgres://localhost/<examples_test>',
migrations: {
directory: './db/migrations'
},
seeds: {
directory: './db/seeds/test'
},
useNullAsDefault: true
},
production: {
client: 'pg',
connection: process.env.DATABASE_URL,
migrations: {
directory: './db/migrations'
},
seeds: {
directory: './db/seeds/production'
},
useNullAsDefault: true
}
}
$ knex migrate:make create-<example>-table
Populate those functions in your migrations/<example>.js
file.
For example:
exports.up = function(knex, Promise) {
let createQuery = `CREATE TABLE <examples>(
id SERIAL PRIMARY KEY NOT NULL,
message TEXT,
created_at TIMESTAMP
)`
return knex.raw(createQuery)
}
exports.down = function(knex, Promise) {
let dropQuery = `DROP TABLE <examples>`
return knex.raw(dropQuery)
}
$ knex migrate:latest
Add --env=test
to migrate your test database.
$ knex seed:make <examples>
Replace the function in seeds/dev/<examples>.js
with your own seeds.d
$ knex seed:run
The following lines may need their paths adjusted depending on where in the project they're used.
const environment = process.env.NODE_ENV || 'development'; // if something else isn't setting ENV, use development
const configuration = require('../knexfile')[environment]; // require environment's settings from knexfile
const database = require('knex')(configuration); // connect to DB via knex using env's settings
You're ready to get devving!
Exactly what I needed, thanks.