简体   繁体   English

如何在迁移中加载Hanami Model?

[英]How to load Hanami Model in a migration?

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. 但是,似乎我需要加载Hanami Model才能使用存储库,因为在运行迁移时Hanami不会加载它。

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? 最大的问题是,如何在Hanami迁移中迁移数据?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM