database_tasks.rb 5.0 KB
Newer Older
1 2
module ActiveRecord
  module Tasks # :nodoc:
3
    class DatabaseAlreadyExists < StandardError; end # :nodoc:
4
    class DatabaseNotSupported < StandardError; end # :nodoc:
5

6 7
    module DatabaseTasks # :nodoc:
      extend self
P
Pat Allan 已提交
8

9 10
      attr_writer :current_config

11
      LOCAL_HOSTS    = ['127.0.0.1', 'localhost']
12

13 14 15 16 17 18 19 20
      def register_task(pattern, task)
        @tasks ||= {}
        @tasks[pattern] = task
      end

      register_task(/mysql/, ActiveRecord::Tasks::MySQLDatabaseTasks)
      register_task(/postgresql/, ActiveRecord::Tasks::PostgreSQLDatabaseTasks)
      register_task(/sqlite/, ActiveRecord::Tasks::SQLiteDatabaseTasks)
K
kennyj 已提交
21
      register_task(/firebird/, ActiveRecord::Tasks::FirebirdDatabaseTasks)
22

23 24 25 26 27 28 29 30 31 32 33 34 35
      def current_config(options = {})
        options.reverse_merge! :env => Rails.env
        if options.has_key?(:config)
          @current_config = options[:config]
        else
          @current_config ||= if ENV['DATABASE_URL']
                                database_url_config
                              else
                                ActiveRecord::Base.configurations[options[:env]]
                              end
        end
      end

36
      def create(*arguments)
37 38
        configuration = arguments.first
        class_for_adapter(configuration['adapter']).new(*arguments).create
39 40
      rescue DatabaseAlreadyExists
        $stderr.puts "#{configuration['database']} already exists"
41 42 43 44
      rescue Exception => error
        $stderr.puts error, *(error.backtrace)
        $stderr.puts "Couldn't create database for #{configuration.inspect}"
      end
P
Pat Allan 已提交
45

46
      def create_all
47 48
        each_local_configuration { |configuration| create configuration }
      end
P
Pat Allan 已提交
49

50
      def create_current(environment = Rails.env)
51 52 53 54 55
        each_current_configuration(environment) { |configuration|
          create configuration
        }
        ActiveRecord::Base.establish_connection environment
      end
P
Pat Allan 已提交
56

57 58 59 60
      def create_database_url
        create database_url_config
      end

61
      def drop(*arguments)
62 63 64 65 66 67
        configuration = arguments.first
        class_for_adapter(configuration['adapter']).new(*arguments).drop
      rescue Exception => error
        $stderr.puts error, *(error.backtrace)
        $stderr.puts "Couldn't drop #{configuration['database']}"
      end
P
Pat Allan 已提交
68

69
      def drop_all
70 71
        each_local_configuration { |configuration| drop configuration }
      end
P
Pat Allan 已提交
72

73
      def drop_current(environment = Rails.env)
74 75 76 77
        each_current_configuration(environment) { |configuration|
          drop configuration
        }
      end
P
Pat Allan 已提交
78

79 80 81 82
      def drop_database_url
        drop database_url_config
      end

S
Simon Jefford 已提交
83 84 85 86 87 88 89 90 91
      def charset_current(environment = Rails.env)
        charset ActiveRecord::Base.configurations[environment]
      end

      def charset(*arguments)
        configuration = arguments.first
        class_for_adapter(configuration['adapter']).new(*arguments).charset
      end

92 93 94 95 96 97 98 99 100
      def collation_current(environment = Rails.env)
        collation ActiveRecord::Base.configurations[environment]
      end

      def collation(*arguments)
        configuration = arguments.first
        class_for_adapter(configuration['adapter']).new(*arguments).collation
      end

101
      def purge(configuration)
102 103
        class_for_adapter(configuration['adapter']).new(configuration).purge
      end
P
Pat Allan 已提交
104

K
kennyj 已提交
105 106 107 108 109 110
      def structure_dump(*arguments)
        configuration = arguments.first
        filename = arguments.delete_at 1
        class_for_adapter(configuration['adapter']).new(*arguments).structure_dump(filename)
      end

K
kennyj 已提交
111 112 113 114 115 116
      def structure_load(*arguments)
        configuration = arguments.first
        filename = arguments.delete_at 1
        class_for_adapter(configuration['adapter']).new(*arguments).structure_load(filename)
      end

117
      private
P
Pat Allan 已提交
118

119 120 121 122 123
      def database_url_config
        @database_url_config ||=
               ConnectionAdapters::ConnectionSpecification::Resolver.new(ENV["DATABASE_URL"], {}).spec.config.stringify_keys
      end

124
      def class_for_adapter(adapter)
125
        key = @tasks.keys.detect { |pattern| adapter[pattern] }
126 127 128
        unless key
          raise DatabaseNotSupported, "Rake tasks not supported by '#{adapter}' adapter"
        end
129
        @tasks[key]
130
      end
P
Pat Allan 已提交
131

132
      def each_current_configuration(environment)
133 134
        environments = [environment]
        environments << 'test' if environment.development?
P
Pat Allan 已提交
135

136 137 138 139 140 141
        configurations = ActiveRecord::Base.configurations.values_at(*environments)
        configurations.compact.each do |configuration|
          yield configuration unless configuration['database'].blank?
        end
      end

142
      def each_local_configuration
143 144
        ActiveRecord::Base.configurations.each_value do |configuration|
          next unless configuration['database']
P
Pat Allan 已提交
145

146 147 148 149 150 151
          if local_database?(configuration)
            yield configuration
          else
            $stderr.puts "This task only modifies local databases. #{configuration['database']} is on a remote host."
          end
        end
P
Pat Allan 已提交
152 153
      end

154
      def local_database?(configuration)
155
        configuration['host'].blank? || LOCAL_HOSTS.include?(configuration['host'])
156 157
      end
    end
P
Pat Allan 已提交
158
  end
159
end