namespace :db do desc "Load environment" task :environment do if ENV['APP_ENV'] == "test" || ENV["RAILS_ENV"] == "test" url = ENV['TEST_DATABASE_URL'] || ENV['TEST_MYSQL_URL'] else url = ENV['DATABASE_URL'] || ENV['MYSQL_URL'] end # some JVM drivers (finagle) don't put user/password in url but as different vars # parse url and add user and password to query string as needed if url.start_with?("jdbc") is_jdbc = true base_url = url.gsub(/^jdbc\:/, "") else is_jdbc = false base_url = url end uri = URI.parse(base_url) query = CGI.parse(uri.query) if !query.has_key?("user") query["user"] = ENV['DATABASE_USERNAME'] || ENV['MYSQL_USERNAME'] end if !query.has_key?("password") password = ENV['DATABASE_PASSWORD'] || ENV['MYSQL_PASSWORD'] query["password"] = password unless password.nil? end uri.query = URI.encode_www_form(query) if is_jdbc uri = "jdbc:" + uri.to_s end ::Sequel::Model.db = ::Sequel.connect(uri) ::Sequel::Model.db.extension(:connection_validator) ::Sequel::Model.db.pool.connection_validation_timeout = 300 end desc "Generate ruby models for all tables" task :generate_models => :environment do Sequel::Model.db.tables.each do |table| klass_name = table.to_s.camelize.singularize klass = Class.new(Sequel::Model(table)) Object.const_set(klass_name, klass) puts "Detected model #{table}" end end desc "Load a console" task :console => :generate_models do ARGV.clear IRB.start end desc "Show version" task :version => :environment do version = if Sequel::Model.db.tables.include?(:schema_migrations) Sequel::Model.db[:schema_migrations].to_a.reverse.first end || {} puts "Schema Version: #{version[:filename]}" end desc "Migrate database" task :migrate, [:version] => :environment do |_, args| Sequel.extension :migration if args[:version] puts "Migrating to version #{args[:version]}" Sequel::Migrator.run(Sequel::Model.db, "db/migrate", target: args[:version].to_i) else puts "Migrating to latest" Sequel::Migrator.run(Sequel::Model.db, "db/migrate") end Rake::Task['db:version'].execute end desc "Rollback database" task :rollback, [:version] => :environment do |_, args| Sequel.extension :migration version = if Sequel::Model.db.tables.include?(:schema_migrations) Sequel::Model.db[:schema_migrations].to_a.sort_by{|x| x["filename"]}.reverse[1] end || {} args.with_defaults(:version => version[:filename]) Sequel::Migrator.run(Sequel::Model.db, "db/migrate", :target => args[:version].to_i) Rake::Task['db:version'].execute end desc "Perform migration reset (full rollback and migration)" task :reset => :environment do Sequel.extension :migration Sequel::Model.db.loggers = [Logger.new($stdout)] Sequel::Migrator.run(Sequel::Model.db, "db/migrate", :target => 0) Sequel::Migrator.run(Sequel::Model.db, "db/migrate") Rake::Task['db:version'].execute end end