我有一个简单的Rake任务,应该终止所有数据库连接,然后从头开始重建应用程序:
namespace :db do
desc "Kill all Postgres connections"
task kill: :environment do
database_name = "#{ENV['APP_NAME']}_development"
puts "killing database #{database_name} ..."
sh = <<EOF
ps xa \
| grep postgres: \
| grep #{database_name} \
| grep -v grep \
| awk '{print $1}' \
| xargs kill
EOF
puts `#{sh}`
end
desc "Rebuild and seed from scratch"
task reup: [:kill, :drop, 'create:all', 'migrate', 'seed']
end
如果我从命令行按顺序运行这些任务,一切都很好,但是如果我运行这个任务,它总是会在迁移任务上窒息:
== 20141027190019 CreatePhotos: migrating =====================================
-- create_table(:photos)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::DuplicateTable: ERROR: relation "photos" already exists
: CREATE TABLE "photos" ("id" serial primary key, "dimensions" character varying(255), "media_item_id" integer, "created_at" timestamp, "updated_at" timestamp) /Users/pedr/.gem/ruby/2.0.0/gems/activerecord-4.1.5/lib/active_record/connection_adapters/postgresql/database_statements.rb:128:in `async_exec'
所以看起来数据库实际上并没有被删除。更奇怪的是,这次迁移是第12次迁移,所以它似乎正在跳过前11次。
即使我手动删除数据库,然后通过尝试运行rake db:migrate
(告诉我数据库不存在)来确认这一点,然后运行rake db:reup
,我得到相同的错误,所以它似乎认为数据库存在,即使它没有。发生此错误后,如果我运行rake db:migrate
,它会成功从开始到结束迁移。
可能出现什么问题?
注意:为reset
交换migrate
工作正常,但我需要重新运行所有迁移。