我们的旧版 Rails 应用程序有一些损坏的迁移(因此我们将迁移整合为一个大型迁移),为其编写了一个 rake 任务,一切都很好。
desc "Removes all schema migrations and inserts the migration reconstruction"
task reconstruct_migrations: :environment do
reconstruction_migration = Dir["db/migrate/*.rb"].find { |migration| migration =~ /reconstruct_database/ }
file_name = reconstruction_migration.split("/").last
timestamp = file_name.split("_").first
puts ">> Resetting migration version to #{timestamp}"
ActiveRecord::Base.transaction do
ActiveRecord::Base.connection.tap do |c|
c.execute("DELETE FROM schema_migrations")
c.execute("INSERT INTO schema_migrations(version) VALUES ('#{timestamp}')")
end
end
end
这有点不正统,但它是大型遗留应用程序,这就是情况。然而,即使在重建我的迁移之后,当运行新的迁移时,它也会失败,因为现有的 MySQL 转储将具有冲突的 schema_migrations 表。它的版本列包含所有先前的迁移时间戳,如下所示:
+----------------+
| version |
+----------------+
| 20081121002510 |
| 20081124055648 |
| 20081124102955 |
| 20081124103008 |
etc....
为了解决我的情况,我需要用 Rails 应用程序中的当前时间戳覆盖此版本列的值。这些是:
200507121201
20151111084520
20151117071001
<小时/>
表格:
mysql> show columns from schema_migrations;
+---------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| version | varchar(255) | NO | PRI | NULL | |
+---------+--------------+------+-----+---------+-------+
1 row in set (0.00 sec)
<小时/>
我尝试解决这个问题:
mysql> UPDATE `schema_migrations` SET `version` = '';
ERROR 1062 (23000): Duplicate entry '' for key 'unique_schema_migrations'
mysql> alter table schema_migrations drop column version;
ERROR 1090 (42000): You can't delete all columns with ALTER TABLE; use DROP TABLE instead
总而言之,我该如何覆盖此列中的现有值并将其替换为上面列出的 3 个值?
最佳答案
看来您需要将所有现有的迁移版本保留在 schema_migrations
中,因为当您下次运行 rake db:migrate
时,Rails 会查找它们。基本上,如果我理解正确,您唯一需要做的就是将重建迁移的时间戳添加到 schema_migrations
。
干杯!
关于MySQL Schema_Migrations - 事件记录 - 更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34085606/