Migrations

and Seeds

Objectives

  • Discuss migrations and seeds
  • Build and run migrations to create tables
  • Build and run seeds to populate data

Migrations

  • Define sets of schema changes
  • Instructions for building tables

Migration Facts

  • Files are generated with a timestamp and run in that order.
  • Think about relationships between resources and generate migrations in a logical order.
  • NEVER MODIFY A MIGRATION FILE AFTER IT HAS BEEN RUN!
  • You can rollback migrations.

Create a Migration


    $ knex migrate:make create_birds

Create a Migration


    exports.up = knex => {
        return knex.schema.createTable('zebras', table => {
            table.increments()
            table.integer('stripes')
            table.string('name')
            table.string('location')
        })
    }

    exports.down = knex => {
      return knex.schema.dropTableIfExists('zebras')
    }

Run Migrations


    $ knex migrate:latest

Seeds

  • Populate your database with test or seed data

Seed Facts

  • Seeds are run in alphanumeric order as well, but feel free to modify the titles. 
  • Order matters if you have relationships in the data; Create seeds that other seeds depend on first.
  • You can modify the contents of seed files.

Create a Seed


    $ knex seed:make birds

Create a Seed


    exports.seed = function(knex) {
      return knex('birds').del()
        .then(function () {
            return knex('birds').insert([
                { name: 'Elmo', top_speed: 45, location: 'Tokyo' },
                { name: 'Mary', top_speed: 112, location: 'Melbourne' },
                { name: 'Peggy', top_speed: 28, location: 'Costa Rica' },
                { name: 'Donovan', top_speed: 60, location: 'Patagonia' },
                { name: 'David', top_speed: 10, location: 'Maui' }
            ])
         })
    }

Run Seeds


    $ knex seed:run

Objectives Review

  • Discuss migrations and seeds
  • Build and run migrations to create tables
  • Build and run seeds to populate data
Made with Slides.com