Search code examples
database-migrationknex.js

How to version seeds in Knex?


I have a sql file where I write sentences for run in release, this file contains sentences like:

-- =======================2019-02-01=======================
UPDATE rating set stars = 3 where id = 6;
UPDATE users SET status = 'A' where last_login >= '2019-01-01';
INSERT INTO....
-- =======================2019-02-15=======================
UPDATE rating set stars = 3 where id = 6;
UPDATE users SET status = 'A' where last_login >= '2019-01-01';
INSERT INTO....

I run specifics sentences in each release date, but I believe that is bad practice and its no escalable method.

I'm trying change this method to Knex seeds or migrations. what would be the best practice to do it?

Seeds have a problem because knex executes the seeds every time I write the command knex seed:run, and it show some errors.


Solution

  • Knex stores the filenames and signatures of what it has executed so that it does not need to run them again.

    https://knexjs.org/#Installation-migrations

    Programmatically you can execute migrations like this:

    knex({..config..}).migrate.latest({
      directory: 'migrations', // where the files are stored
      tableName: 'knex_migrations' // where knex saves its records
    });
    

    Example migration file

    exports.up = function(knex) {
      return knex.raw(`
       UPDATE rating set stars = 3 where id = 6;
       UPDATE users SET status = 'A' where last_login >= '2019-01-01';
       INSERT INTO....
      `)
    };
    

    The files will be executed alphabetically/sorted, and will not be re-executed against the same database.