Search code examples
database-migrationknex.jsrollback

Tables are not dropped when rolling back migration


When I execute the rollback command from Knex it only removes rows from the knex_migrations table but not the tables created by the migrations.

I'm using MySQL, but the same happens with SQLite3.

GitHub repository: https://github.com/patrick-vieira/knex-rollback

First migration:

import * as Knex from 'knex';

export async function up(knex: Knex): Promise<void>{
  return knex.schema.createTable('users', table => {

    table.increments('id').primary();
    
    table.string('name').notNullable();
    table.string('avatar').notNullable();
    table.string('whatsapp').notNullable();
    table.string('bio').notNullable();
  });
}

// roolback
export async function down(knex: Knex): Promise<void> {
  knex.schema.dropTable('users');
}

Solution

  • You always need to return the result of your knex operation from the up and down functions. If you look at the example I've edited into your question, you'll see that you use the return statement in up, but not in down.

    Further, migrations return a schema builder (not void). I don't normally write migrations in TS, but I think what you're looking for, signature-wise, is something like:

    import Knex, { SchemaBuilder } from 'knex'
    
    export const up = (knex: Knex): SchemaBuilder => {
      return knex.schema.createTable( // ... etc ...
    }
    

    A trick to ensure you always remember to return the result is to leverage arrow function auto-return:

    export const up = (knex: Knex) => knex.schema.createTable(
      // ... etc ...