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 17
    config.app_generators.orm :active_record, migration: true,
                                              timestamps: true
18

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

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

29 30
    config.eager_load_namespaces << ActiveRecord

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

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

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

47 48 49
    # 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.
50 51
    console do |app|
      require "active_record/railties/console_sandbox" if app.sandbox?
K
kennyj 已提交
52
      require "active_record/base"
53 54 55 56
      unless ActiveSupport::Logger.logger_outputs_to?(Rails.logger, STDERR, STDOUT)
        console = ActiveSupport::Logger.new(STDERR)
        Rails.logger.extend ActiveSupport::Logger.broadcast console
      end
57 58
    end

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

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

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

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

81
    initializer "active_record.check_schema_cache_dump" do
82 83 84 85
      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")
86

87 88 89
            if File.file?(filename)
              cache = Marshal.load File.binread filename
              if cache.version == ActiveRecord::Migrator.current_version
J
Jon Leighton 已提交
90
                self.connection.schema_cache = cache
91
                self.connection_pool.schema_cache = cache.dup
92
              else
93
                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}."
94 95 96 97 98 99 100
              end
            end
          end
        end
      end
    end

101 102 103
    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
104
          require "active_record/relation/record_fetch_warning"
105 106 107 108
        end
      end
    end

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

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

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

129 130 131
Here's how to get started:

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

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

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

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

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