thuss / standalone-migrations

A gem to use Rails Database Migrations in non Rails projects
http://gabrito.com/post/standalone-migrations-using-rails-migrations-in-non-rails-projects
MIT License
992 stars 152 forks source link

"Changing environment config in runtime" not working #148

Open landovsky opened 6 years ago

landovsky commented 6 years ago

Having this

.env vars

DATABASE_URL_TEST=postgres://postgres:hele@postgres/techloop_automator_testik

db/config.yml

test:
  database: techloop_automator_test
  ...

Rakefile

require 'standalone_migrations'

StandaloneMigrations::Tasks.load_tasks

StandaloneMigrations::Configurator.environments_config do |env|
  env.on "test" do
    if (ENV['DATABASE_URL_TEST  '])
      db = URI.parse(ENV['DATABASE_URL_TEST'])
      return {
        :adapter  => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
        :host     => db.host,
        :username => db.user,
        :password => db.password,
        :database => db.path[1..-1],
        :encoding => 'utf8'
      }
    end

    nil
  end
end

When I run rake db:create RAILS_ENV=test, I get:

root@f0db907210df:/automator# rake db:create RAILS_ENV=test
Created database 'techloop_automator_test'

>> it creates techloop_automator_test as opposed to techloop_automator_testik

lacostenycoder commented 6 years ago

Why are you using a different name in DATABASE_URL_TEST=postgres://postgres:hele@postgres/techloop_automator_testik than in your config? Did you try changing in yaml file

test:
  database: techloop_automator_testik

But also maybe try setting the config before loading the tasks? So move StandaloneMigrations::Tasks.load_tasks to after your config do/end block.

mattes commented 5 years ago

Same issue here. Here is a snippet that worked for me:

require 'tasks/standalone_migrations'
require 'yaml'

StandaloneMigrations::Configurator.environments_config do |env|
  f = YAML.load_file('config.yml')
  db = URI.parse(f['postgres'])
  env.on "default" do |c|
    c["adapter"]  = db.scheme == 'postgres' ? 'postgresql' : db.scheme
    c["host"]     = db.host
    c["port"]     = db.port
    c["username"] = db.user
    c["password"] = db.password
    c["database"] = db.path[1..-1]
    c["encoding"] = 'utf8'
    return c
  end
end