2

I want to change a structure of a table in a table and I need to backfill some new fields with the values of the old ones. So, for that, I want to use the repository in the migration. But, it seems that I need to load Hanami Model to use a repository since Hanami does not load it when running the migration.

So, right now I have this:

require_relative '../../lib/my_app/repositories/entity_repository'
require_relative '../../lib/my_app/entities/my_entity'

Mutex.new.synchronize do
  Hanami::Model.load!
end

Hanami::Model.migration do
  change do
    def backfill_data!
      repo = EntityRepository.new

      repo.all.map do |entity|
        repo.update entity.id, new_field_as_date: Date.new(entity.old_field)
      end
    end

    backfill_data!
  end
end

But when running this migration, I get

bundler: failed to load command: hanami (/Users/user/.rbenv/versions/2.4.1/bin/hanami)
Hanami::Model::Error: key not found: :person
# which is an association with the entity mentioned on the code

So, I have no idea what to do now. The big question is, how to migrate data on Hanami migrations?

rafaels88
  • 839
  • 1
  • 6
  • 19

1 Answers1

3

I don't know about this specific issue, but I strongly discourage you do use repositories in migrations. Because a repository is tight to the current schema of a database table, it may not work if you run the same migration in the future.

You should use database facilities directly. That would guarantee the migration to always work:

Hanami::Model.migration do
  up do
    run "UPDATE users SET last_login_at=(last_login_at - INTERVAL '1 day')"
  end

  down do
  end
end
Luca Guidi
  • 1,201
  • 10
  • 10
  • Thanks for the answer, Luca. In fact, I solved my problem using SQL as you mentioned, but I was thinking that would be good to use repositories since I would have a database agnostic migration, taking advantage of the Hanami Model encapsulation for the database driver. But thats fine! – rafaels88 Oct 06 '17 at 15:50