railtie.rb 5.8 KB
Newer Older
1 2 3 4
require "active_record"
require "rails"
require "active_model/railtie"

5
# For now, action_controller must always be present with
S
Santosh Wadghule 已提交
6
# Rails, so let's make sure that it gets required before
7 8
# here. This is needed for correctly setting up the middleware.
# In the future, this might become an optional require.
C
Carl Lerche 已提交
9
require "action_controller/railtie"
10 11

module ActiveRecord
R
Rizwan Reza 已提交
12
  # = Active Record Railtie
13
  class Railtie < Rails::Railtie # :nodoc:
14
    config.active_record = ActiveSupport::OrderedOptions.new
15

16
    config.app_generators.orm :active_record, :migration => true,
17
                                              :timestamps => true
18

19 20 21 22 23 24 25
    config.action_dispatch.rescue_responses.merge!(
      'ActiveRecord::RecordNotFound'   => :not_found,
      'ActiveRecord::StaleObjectError' => :conflict,
      'ActiveRecord::RecordInvalid'    => :unprocessable_entity,
      'ActiveRecord::RecordNotSaved'   => :unprocessable_entity
    )

26

27
    config.active_record.use_schema_cache_dump = true
28
    config.active_record.maintain_test_schema = true
29

30 31
    config.eager_load_namespaces << ActiveRecord

32
    rake_tasks do
33 34
      namespace :db do
        task :load_config do
35
          ActiveRecord::Tasks::DatabaseTasks.database_configuration = Rails.application.config.database_configuration
36

37
          if defined?(ENGINE_ROOT) && engine = Rails::Engine.find(ENGINE_ROOT)
38 39 40 41
            if engine.paths['db/migrate'].existent
              ActiveRecord::Tasks::DatabaseTasks.migrations_paths += engine.paths['db/migrate'].to_a
            end
          end
42 43 44
        end
      end

45
      load "active_record/railties/databases.rake"
46 47
    end

48 49 50
    # When loading console, force ActiveRecord::Base to be loaded
    # to avoid cross references when loading a constant for the
    # first time. Also, make it output to STDERR.
51 52
    console do |app|
      require "active_record/railties/console_sandbox" if app.sandbox?
K
kennyj 已提交
53
      require "active_record/base"
54 55 56 57
      unless ActiveSupport::Logger.logger_outputs_to?(Rails.logger, STDERR, STDOUT)
        console = ActiveSupport::Logger.new(STDERR)
        Rails.logger.extend ActiveSupport::Logger.broadcast console
      end
58 59
    end

V
Vipul A M 已提交
60
    runner do
61 62 63
      require "active_record/base"
    end

64
    initializer "active_record.initialize_timezone" do
65
      ActiveSupport.on_load(:active_record) do
66 67 68
        self.time_zone_aware_attributes = true
        self.default_timezone = :utc
      end
69 70
    end

71
    initializer "active_record.logger" do
72
      ActiveSupport.on_load(:active_record) { self.logger ||= ::Rails.logger }
73 74
    end

V
Vipul A M 已提交
75
    initializer "active_record.migration_error" do
S
schneems 已提交
76
      if config.active_record.delete(:migration_error) == :page_load
M
Miles Starkenburg 已提交
77
        config.app_middleware.insert_after ::ActionDispatch::Callbacks,
78
          ActiveRecord::Migration::CheckPending
S
schneems 已提交
79 80 81
      end
    end

82
    initializer "active_record.check_schema_cache_dump" do
83 84 85 86
      if config.active_record.delete(:use_schema_cache_dump)
        config.after_initialize do |app|
          ActiveSupport.on_load(:active_record) do
            filename = File.join(app.config.paths["db"].first, "schema_cache.dump")
87

88 89 90
            if File.file?(filename)
              cache = Marshal.load File.binread filename
              if cache.version == ActiveRecord::Migrator.current_version
J
Jon Leighton 已提交
91
                self.connection.schema_cache = cache
92
                self.connection_pool.schema_cache = cache.dup
93
              else
94
                warn "Ignoring db/schema_cache.dump because it has expired. The current schema version is #{ActiveRecord::Migrator.current_version}, but the one in the cache is #{cache.version}."
95 96 97 98 99 100 101
              end
            end
          end
        end
      end
    end

102 103 104 105 106 107 108 109
    initializer "active_record.warn_on_records_fetched_greater_than" do
      if config.active_record.warn_on_records_fetched_greater_than
        ActiveSupport.on_load(:active_record) do
          require 'active_record/relation/record_fetch_warning'
        end
      end
    end

110
    initializer "active_record.set_configs" do |app|
111
      ActiveSupport.on_load(:active_record) do
112 113 114
        app.config.active_record.each do |k,v|
          send "#{k}=", v
        end
115 116 117 118 119
      end
    end

    # This sets the database configuration from Configuration#database_configuration
    # and then establishes the connection.
A
amitkumarsuroliya 已提交
120
    initializer "active_record.initialize_database" do
121
      ActiveSupport.on_load(:active_record) do
122
        self.configurations = Rails.application.config.database_configuration
123

124 125 126 127 128
        begin
          establish_connection
        rescue ActiveRecord::NoDatabaseError
          warn <<-end_warning
Oops - You have a database configured, but it doesn't exist yet!
129

130 131 132
Here's how to get started:

  1. Configure your database in config/database.yml.
133 134
  2. Run `bin/rails db:create` to create the database.
  3. Run `bin/rails db:setup` to load your database schema.
135 136 137
end_warning
          raise
        end
138
      end
139 140
    end

141
    # Expose database runtime to controller for logging.
V
Vipul A M 已提交
142
    initializer "active_record.log_runtime" do
143
      require "active_record/railties/controller_runtime"
144
      ActiveSupport.on_load(:action_controller) do
145 146
        include ActiveRecord::Railties::ControllerRuntime
      end
147 148
    end

149
    initializer "active_record.set_reloader_hooks" do
J
Jon Leighton 已提交
150
      ActiveSupport.on_load(:active_record) do
151
        ActiveSupport::Reloader.before_class_unload do
152 153
          if ActiveRecord::Base.connected?
            ActiveRecord::Base.clear_cache!
154
            ActiveRecord::Base.clear_reloadable_connections!
155
          end
156
        end
157 158 159
      end
    end

160 161 162 163 164 165
    initializer "active_record.set_executor_hooks" do
      ActiveSupport.on_load(:active_record) do
        ActiveRecord::QueryCache.install_executor_hooks
      end
    end

166
    initializer "active_record.add_watchable_files" do |app|
167 168
      path = app.paths["db"].first
      config.watchable_files.concat ["#{path}/schema.rb", "#{path}/structure.sql"]
169
    end
170
  end
171
end