Skip to content

jamiesonbates/knex-migrations-seeds-demo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Knex Migrations and Seeds Demo

Setup

Clone repo:

git clone https://github.com/jamiesonbates/knex-migrations-seeds-demo.git
npm install

Setup DB:

createdb cities_dev

Configure knexfile && knex commands

Utilize reading/article to:

  • Configure knexfile.js so that you can connect to your database.
  • Add a knex command to "scripts" within package.json

Create a Migration

Create a migration file for a table named "cities."

npm run knex migrate:make cities

You should see something like this:

Translate the following entity relationship diagram into a Knex migration file.

┌──────────────────────────────────────────────────────────────────────────────────────────┐
│                                          cities                                           │
├─────────────┬─────────────────────────┬──────────────────────────────────────────────────┤
│id           │serial                   │primary key                                       │
│name         │varchar(255)             │not null default ''                               │
│state        │varchar(255)             │not null default ''                               │
│population   │integer                  │                                                  │
│created_at   │timestamp with time zone │not null default now()                            │
│updated_at   │timestamp with time zone │not null default now()                            │
└─────────────┴─────────────────────────┴──────────────────────────────────────────────────┘

When you have built a migration file, use the following command to migrate the database:

npm run knex migrate:latest

If successful, you should see something like this:

Also run this command to view information about the created table:

psql cities_dev -c '\d cities'

This command should result in something like this:

Create a Seed

Use the following data to create a seed for the table named "cities."

Create the seed file:

npm run knex seed:make 1_cities

You should see something like this:

Next, utilize the following data to build out your seed file:

const cities = [
  {
    name: 'Seattle',
    state: 'Washington',
    population: 704352
  },
  {
    name: 'Tacoma',
    state: 'Washington',
    population: 211277
  },
  {
    name: 'Bellingham',
    state: 'Washington',
    population: 87574
  }
]

When you're read to seed your database, run the following command:

npm run knex seed:run

You should see something like this:

Also, run the following command to see the contents of your database:

psql cities_dev -c 'SELECT * FROM cities';

You should see something like this:

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published