database_tasks.rb 5.2 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
      def register_task(pattern, task)
        @tasks ||= {}
        @tasks[pattern] = task
      end

K
kennyj 已提交
18 19 20
      register_task(/mysql/,        ActiveRecord::Tasks::MySQLDatabaseTasks)
      register_task(/postgresql/,   ActiveRecord::Tasks::PostgreSQLDatabaseTasks)
      register_task(/sqlite/,       ActiveRecord::Tasks::SQLiteDatabaseTasks)
K
kennyj 已提交
21

K
kennyj 已提交
22 23 24
      register_task(/firebird/,     ActiveRecord::Tasks::FirebirdDatabaseTasks)
      register_task(/sqlserver/,    ActiveRecord::Tasks::SqlserverDatabaseTasks)
      register_task(/(oci|oracle)/, ActiveRecord::Tasks::OracleDatabaseTasks)
25

26 27 28 29 30 31 32 33 34 35 36 37 38
      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

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

49
      def create_all
50 51
        each_local_configuration { |configuration| create configuration }
      end
P
Pat Allan 已提交
52

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

60 61 62 63
      def create_database_url
        create database_url_config
      end

64
      def drop(*arguments)
65 66 67 68 69 70
        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 已提交
71

72
      def drop_all
73 74
        each_local_configuration { |configuration| drop configuration }
      end
P
Pat Allan 已提交
75

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

82 83 84 85
      def drop_database_url
        drop database_url_config
      end

S
Simon Jefford 已提交
86 87 88 89 90 91 92 93 94
      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

95 96 97 98 99 100 101 102 103
      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

104
      def purge(configuration)
105 106
        class_for_adapter(configuration['adapter']).new(configuration).purge
      end
P
Pat Allan 已提交
107

K
kennyj 已提交
108 109 110 111 112 113
      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 已提交
114 115 116 117 118 119
      def structure_load(*arguments)
        configuration = arguments.first
        filename = arguments.delete_at 1
        class_for_adapter(configuration['adapter']).new(*arguments).structure_load(filename)
      end

120
      private
P
Pat Allan 已提交
121

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

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

135
      def each_current_configuration(environment)
136 137
        environments = [environment]
        environments << 'test' if environment.development?
P
Pat Allan 已提交
138

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

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

149 150 151 152 153 154
          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 已提交
155 156
      end

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