Search code examples
databaseknex.js

Update Knex.js table without loosing data


I am uncertain how to change your tables in your schema with Knex.js. Currently I have a table that looks like this:

.createTable('users', function(table) {
  table.increments('id')
  table
    .text('username')
    .notNullable()
    .unique()
  table.text('name')
  table
    .text('email')
    .notNullable()
    .unique()
  table.string('password').notNullable()
  table
    .text('profile_image')
    .defaultTo('http://www.ecehh.org/wp-content/uploads/2018/02/avatar.jpg')

What I'd like to do is change the defaultTo at the profile_image. I read from here http://perkframework.com/v1/guides/database-migrations-knex.html that "We never want to edit a migration file after it has been run because when we run knex migrate:latest knex will not make the change. Migrations will only run once." So I wonder how I should update it's value without re-running the migration and then loose all of my current data.

Thanks for reading!


Solution

  • Is it a production server?

    From this issue I think this can work.

    exports.up = knex => {
      return knex.schema
        .alterTable('users', table => {
          table.text('profile_image').defaultTo('myurl').alter()
      });
    };
    
    exports.down = knex => {
      return knex.schema.alterTable('users', table => {
          table.text('profile_image').defaultTo('myurl').alter()
      });
    };