BigW Consortium Gitlab

db.rake 2.6 KB
Newer Older
1 2 3 4 5
namespace :gitlab do
  namespace :db do
    desc 'GitLab | Manually insert schema migration version'
    task :mark_migration_complete, [:version] => :environment do |_, args|
      unless args[:version]
6
        puts "Must specify a migration version as an argument".color(:red)
7 8 9 10 11
        exit 1
      end

      version = args[:version].to_i
      if version == 0
12
        puts "Version '#{args[:version]}' must be a non-zero integer".color(:red)
13 14 15 16 17 18
        exit 1
      end

      sql = "INSERT INTO schema_migrations (version) VALUES (#{version})"
      begin
        ActiveRecord::Base.connection.execute(sql)
19
        puts "Successfully marked '#{version}' as complete".color(:green)
20
      rescue ActiveRecord::RecordNotUnique
21
        puts "Migration version '#{version}' is already marked complete".color(:yellow)
22 23 24 25 26 27
      end
    end

    desc 'Drop all tables'
    task :drop_tables => :environment do
      connection = ActiveRecord::Base.connection
28 29 30 31

      # If MySQL, turn off foreign key checks
      connection.execute('SET FOREIGN_KEY_CHECKS=0') if Gitlab::Database.mysql?

32 33 34 35
      tables = connection.tables
      tables.delete 'schema_migrations'
      # Truncate schema_migrations to ensure migrations re-run
      connection.execute('TRUNCATE schema_migrations')
36

37 38 39
      # Drop tables with cascade to avoid dependent table errors
      # PG: http://www.postgresql.org/docs/current/static/ddl-depend.html
      # MySQL: http://dev.mysql.com/doc/refman/5.7/en/drop-table.html
40
      # Add `IF EXISTS` because cascade could have already deleted a table.
41
      tables.each { |t| connection.execute("DROP TABLE IF EXISTS #{connection.quote_table_name(t)} CASCADE") }
42 43 44

      # If MySQL, re-enable foreign key checks
      connection.execute('SET FOREIGN_KEY_CHECKS=1') if Gitlab::Database.mysql?
45
    end
46 47

    desc 'Configures the database by running migrate, or by loading the schema and seeding if needed'
48
    task configure: :environment do
49
      if ActiveRecord::Base.connection.tables.any?
50 51 52 53 54 55
        Rake::Task['db:migrate'].invoke
      else
        Rake::Task['db:schema:load'].invoke
        Rake::Task['db:seed_fu'].invoke
      end
    end
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

    desc 'Checks if migrations require downtime or not'
    task :downtime_check, [:ref] => :environment do |_, args|
      abort 'You must specify a Git reference to compare with' unless args[:ref]

      require 'shellwords'

      ref = Shellwords.escape(args[:ref])

      migrations = `git diff #{ref}.. --name-only -- db/migrate`.lines.
        map { |file| Rails.root.join(file.strip).to_s }.
        select { |file| File.file?(file) }

      Gitlab::DowntimeCheck.new.check_and_print(migrations)
    end
71 72
  end
end