-
Notifications
You must be signed in to change notification settings - Fork 4
/
Rakefile
79 lines (68 loc) · 2.24 KB
/
Rakefile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# This file based on:
# https://github.com/andhapp/activerecord_sans_rails
# https://gist.github.com/schickling/6762581
require "yaml"
require "sqlite3"
require "active_record"
require "./models/application_record.rb"
# command list:
# `rake db:migrate`
# `rake db:rollback`
# `rake db:schema`
namespace :db do
task :environment do
APP_ENV = ENV['APP_ENV'] || 'development'
DB_DIR = "#{Rake.application.original_dir}/db"
DB_CONFIG_PATH = "#{Rake.application.original_dir}/config/database.yml"
DB_CONFIG = YAML::load(File.open(DB_CONFIG_PATH))[APP_ENV]
end
desc "Migrate the database"
task migrate: :environment do
ActiveRecord::Base.establish_connection(DB_CONFIG)
ActiveRecord::MigrationContext.new("#{DB_DIR}/migrate/", ActiveRecord::SchemaMigration).migrate
Rake::Task["db:schema"].invoke
puts "Database migrated."
end
desc "Rollback the database"
task rollback: :environment do
ActiveRecord::Base.establish_connection(DB_CONFIG)
ActiveRecord::MigrationContext.new("#{DB_DIR}/migrate/", ActiveRecord::SchemaMigration).rollback
Rake::Task["db:schema"].invoke
puts "Last migration has been reverted."
end
desc 'Create a db/schema.rb file that is portable against any DB supported by AR'
task schema: :environment do
ActiveRecord::Base.establish_connection(DB_CONFIG)
require 'active_record/schema_dumper'
filename = "#{DB_DIR}/schema.rb"
File.open(filename, "w:utf-8") do |file|
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
end
end
task 'migrate:up'
task 'migrate:down'
task 'migrate:reset'
task 'migrate:redo'
end
# command: `rake g:migration your_migration`
namespace :g do
desc "Generate migration"
task migration: :"db:environment" do
name = ARGV[1] || raise("Specify name: rake g:migration your_migration")
timestamp = Time.now.strftime("%Y%m%d%H%M%S")
path = File.expand_path("#{DB_DIR}/migrate/#{timestamp}_#{name}.rb", __FILE__)
migration_class = name.split("_").map(&:camelize).join
File.open(path, 'w') do |file|
file.write <<-EOF
class #{migration_class} < ActiveRecord::Migration[6.0]
def up
end
def down
end
end
EOF
end
puts "Migration #{path} created"
abort # needed stop other tasks
end
end