Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Migrations With Knex.js In My Node.js Application

I am trying to get knex working in my node.js application. I was following a tutorial and at some point created a table but could not repeat the process. I removed the table and deleted all the migrations folders. At tis point I started over but after creating a new migration and then running knex migrate:latest I get an error saying the migration directory is corrupt because the original migration I had is missing.

I was under the impression that if the file is missing it should not know it was ever there.

What is the proper way to remove a migration from my project?

knexfile.js

 development: {
    client: 'pg',
    connection: {
    host: '127.0.0.1',
    user:     'postgres',
    password: 'password',
    database: 'myDatabase'
    },
     pool: {
      min: 10,
      max: 20
    },
    migrations: {
      directory: __dirname + '/db/migrations'
    },
    seeds: {
      directory: __dirname + '/db/seeds/development'
    }

db.js

var config      = require('../knexfile.js');  
var env         = 'development';  
var knex        = require('knex')(config[env]);

module.exports = knex;
console.log('Getting knex');
knex.migrate.latest([config]); 
console.log('Applying migration...');

Running this gives error,

knex migrate:latest

Using environment: development
Error: The migration directory is corrupt, the following files are missing: 20161110130954_auth_level.js

but this migration does not exist because I deleted it.

like image 628
wuno Avatar asked Nov 11 '16 19:11

wuno


4 Answers

You had to rollback a migration (knex migrate:rollback) before deleting the file, I guess what you can do is:

touch [full_path_to_migrations_here]/migrations/20161110130954_auth_level.js

knex migrate:rollback

rm [full_path_to_migrations_here]/migrations/20161110130954_auth_level.js

Reference here https://github.com/tgriesser/knex/issues/1569

like image 174
marman Avatar answered Nov 09 '22 23:11

marman


Your migration files have been deleted, but they are still referenced in a table called "migrations"
(see update below), which was generated by knex.

You should be able to check it by connecting to your local database.

I faced the same problem and I solved it by removing records corresponding to my deleted migration files.

delete from migrations
where migrations."name" in ('20191027220145_your_migration_file.js', ...);

EDIT: The migrations table name might change according to the options or to the version you use.
The constant is set here and used there.
To be sure of the name, you could list all tables as suggested by @MohamedAllal.

Hope it helps

like image 39
fservantdev Avatar answered Nov 10 '22 00:11

fservantdev


To remove either you can rollback and so rollback then remove.

Or you can not ! And follow on the bellow:

(> The bellow, answer too the following error which you may already get to see:<)

Error: The migration directory is corrupt

Which will happens if

The migrations files are deleted, while the records on the migration table created by knex remains there!

So simply clear them up!

(remove then clear up, or clear up then remove!)

Important to note the migration table by now is knex_migration. Don't know if it was different in the past!

But better list the db tables to make sure!

I'm using postgres! Using psql :

> \d

i get :

enter image description here

You can do it with Raw SQL! Using your db terminal client, Or using knex itself! Or any other means (an editor client (pgAdmin, mysql workbench, ...).

Raw sql

DELETE FROM knex_migration
WHERE knex_migration."name" IN ('20200425190608_yourMigFile.ts', ...);

Note you can copy past the files from the error message (if you get it)

ex: 20200425190608_creazteUserTable.ts, 20200425193758_createTestTestTable.ts

from

Error: The migration directory is corrupt, the following files are missing: 20200425190608_creazteUserTable.ts, 20200425193758_createTestTestTable.ts

Copy past! And it's fast!

(you can get the error by trying to migrate)

Using knex itself

knex('knex_migration')
    .delete()
    .whereIn('name', ['20200425190608_yourMigFile.ts', ...]);

Create a script! Call your knex instance! Done! Cool!

After cleaning

enter image description here

The migrations will run nicely! And your directory no more corrupt! How much i do love that green!

Happy coding!

Removing a migration: (Bring it down then remove to remove)

What is the right way to remove a migration?

The answer is bring that one migration down and then remove it's file!

Illustration

$ knex migrate:down "20200520092308_createUsersWorksTable.ts"

$ rm migrations/20200520092308_createUsersWorksTable.ts

enter image description here

You can list the migrations to check as bellow

$ knex migrate:list

(from v0.19.3! if not available update knex (npm i -g knex))

Alter migration to alter only (No)

If you are like me and like to update the migration directly in the base migration! And you may think about creating an alter migration! run it then remove it!

A fast flow! You just make the update on the base creation table! Copy past into the new created alter table! And run it then remove it!

If you're thinking that way! Don't !!!

You can't rollback because it's the changes that you want! You can't cancel them!

You can do it! And then you have to clear the records! Or you'll get the error! And just not cool!

Better create an later file script! Not a migration file! And run it directly! Done!

My preference is to create an alter.ts (.js) file in the Database folder! Then create the alter schema code there! And create an npm script to run it!

enter image description here

Each time you just modify it! And run!

Here the base skeleton:

import knex from './db';

(async () => {
    try {
        const resp = await knex.schema.alterTable('transactions', (table) => {
            table.decimal('feeAmount', null).nullable();
        });
        console.log(resp);
    } catch (err) {
        console.log(err);
    }
})();

And better with vscode i just use run code (if run code extension is installed! Which is a must hhhh)!

enter image description here

And if no errors then it run well! And you can check the response!

You can check up the schema api in the doc!

Also to alter you'll need to use alter() method as by the snippet bellow that i took from the doc:

// ________________ alter fields
// drops previous default value from column, change type
// to string and add not nullable constraint
table.string('username', 35).notNullable().alter();
// drops both not null constraint and the default value
table.integer('age').alter();

Now happy coding!

like image 21
Mohamed Allal Avatar answered Nov 10 '22 01:11

Mohamed Allal


try to use the option below, it will do exactly what it refers to:

migrations: {
 disableMigrationsListValidation: true,
}

knex.js migration api

like image 37
M. Emre Yalçın Avatar answered Nov 10 '22 01:11

M. Emre Yalçın