require 'active_record' require 'rubypitaya/core/path' require 'rubypitaya/core/database_config' namespace :db do desc 'Create the database' task :create do environment_name = ENV.fetch("RUBYPITAYA_ENV") { 'development' } database_config = RubyPitaya::DatabaseConfig.new(environment_name, RubyPitaya::Path::DATABASE_CONFIG_PATH) connection_data = database_config.connection_data_without_database ActiveRecord::Base.establish_connection(connection_data) ActiveRecord::Base.connection.create_database(database_config.database_name) ActiveRecord::Base.connection.close puts 'Database created.' end desc 'Migrate the database' task :migrate do environment_name = ENV.fetch("RUBYPITAYA_ENV") { 'development' } database_config = RubyPitaya::DatabaseConfig.new(environment_name, RubyPitaya::Path::DATABASE_CONFIG_PATH) connection_data = database_config.connection_data migrations_paths = [RubyPitaya::Path::Core::MIGRATIONS_FOLDER_PATH] migrations_paths += RubyPitaya::Path::Plugins::MIGRATIONS_FOLDER_PATHS migrations_paths += [RubyPitaya::Path::MIGRATIONS_FOLDER_PATH] ActiveRecord::Base.establish_connection(connection_data) ActiveRecord::Migrator.migrations_paths = migrations_paths ActiveRecord::Tasks::DatabaseTasks.migrate ActiveRecord::Base.connection.close puts 'Database migrated.' end desc 'Rollback migrations' task :rollback do environment_name = ENV.fetch("RUBYPITAYA_ENV") { 'development' } database_config = RubyPitaya::DatabaseConfig.new(environment_name, RubyPitaya::Path::DATABASE_CONFIG_PATH) connection_data = database_config.connection_data migrations_paths = [RubyPitaya::Path::Core::MIGRATIONS_FOLDER_PATH] migrations_paths += RubyPitaya::Path::Plugins::MIGRATIONS_FOLDER_PATHS migrations_paths += [RubyPitaya::Path::MIGRATIONS_FOLDER_PATH] step = ENV["STEP"] ? ENV["STEP"].to_i : 1 if step == 0 puts '' puts 'Error: No rollback to STEP=0' puts '' return end ActiveRecord::Base.establish_connection(connection_data) ActiveRecord::Migrator.migrations_paths = migrations_paths ActiveRecord::Base.connection.migration_context.rollback(step) ActiveRecord::Base.connection.close puts 'Rollback done.' end desc 'Drop the database' task :drop do environment_name = ENV.fetch("RUBYPITAYA_ENV") { 'development' } database_config = RubyPitaya::DatabaseConfig.new(environment_name, RubyPitaya::Path::DATABASE_CONFIG_PATH) connection_data = database_config.connection_data_without_database ActiveRecord::Base.establish_connection(connection_data) ActiveRecord::Base.connection.select_all "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE datname='#{database_config.database_name}' AND pid <> pg_backend_pid();" ActiveRecord::Base.connection.drop_database(database_config.database_name) ActiveRecord::Base.connection.close puts 'Database deleted.' end desc 'Reset the database' task :reset do Rake::Task['db:drop'].invoke Rake::Task['db:create'].invoke Rake::Task['db:migrate'].invoke puts 'Database reset finish.' end end