Using Migrations to Modify Data in Production

The initial work on a project is always easier when it comes to the database and data therein. Things change a bit after going live, where a migration could potentially cause loss of data, or a migration would also require some data to be moved elsewhere or even modified.

I've always seen migrations as a thing to modify the database schema, and never to modify the actual data. Recently, however, we've had to do a larger upgrade on a live project, so I decided to search for a solution. Before many searches on Google, I realized that I could just use a migration, considering that it will run just after deploying the code.

I won't be showing any concrete examples here, first because migrations are handled differently between frameworks and code bases, and second because it's fairly straightforward. To give you a rough idea, it may look like this:

<?php

class ModifyUserApiVersionMigration {

    public function up() {
        DB::table('users')
            ->where('created_at', '>=', '2017-01-01 00:00:00')
            ->update(['api_version' => 2]);
    }

    public function down() {
        DB::table('users')
            ->where('created_at', '>=', '2017-01-01 00:00:00')
            ->update(['api_version' => 1]);
    }

}

Normally, I wouldn't use down migrations, and so wouldn't some people that are much smarter than me. Usually, I would just write another up migration and solve any issues. I added it to illustrate what you could do.

I hope this gave you some ideas on how to manage data after going live.

Show Comments