railtie.rb 8.5 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5 6
require "active_record"
require "rails"
require "active_model/railtie"

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

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

18 19
    config.app_generators.orm :active_record, migration: true,
                                              timestamps: true
20

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

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

31 32 33
    config.active_record.sqlite3 = ActiveSupport::OrderedOptions.new
    config.active_record.sqlite3.represent_boolean_as_integer = nil

34 35
    config.eager_load_namespaces << ActiveRecord

36
    rake_tasks do
37 38
      namespace :db do
        task :load_config do
39
          ActiveRecord::Tasks::DatabaseTasks.database_configuration = Rails.application.config.database_configuration
40

41
          if defined?(ENGINE_ROOT) && engine = Rails::Engine.find(ENGINE_ROOT)
42 43
            if engine.paths["db/migrate"].existent
              ActiveRecord::Tasks::DatabaseTasks.migrations_paths += engine.paths["db/migrate"].to_a
44 45
            end
          end
46 47 48
        end
      end

49
      load "active_record/railties/databases.rake"
50 51
    end

52 53 54
    # 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.
55
    console do |app|
56 57
      require "active_record/railties/console_sandbox" if app.sandbox?
      require "active_record/base"
58 59 60 61
      unless ActiveSupport::Logger.logger_outputs_to?(Rails.logger, STDERR, STDOUT)
        console = ActiveSupport::Logger.new(STDERR)
        Rails.logger.extend ActiveSupport::Logger.broadcast console
      end
62
      ActiveRecord::Base.verbose_query_logs = false
63 64
    end

V
Vipul A M 已提交
65
    runner do
66
      require "active_record/base"
67 68
    end

69
    initializer "active_record.initialize_timezone" do
70
      ActiveSupport.on_load(:active_record) do
71 72 73
        self.time_zone_aware_attributes = true
        self.default_timezone = :utc
      end
74 75
    end

76
    initializer "active_record.logger" do
77
      ActiveSupport.on_load(:active_record) { self.logger ||= ::Rails.logger }
78 79
    end

V
Vipul A M 已提交
80
    initializer "active_record.migration_error" do
S
schneems 已提交
81
      if config.active_record.delete(:migration_error) == :page_load
M
Miles Starkenburg 已提交
82
        config.app_middleware.insert_after ::ActionDispatch::Callbacks,
83
          ActiveRecord::Migration::CheckPending
S
schneems 已提交
84 85 86
      end
    end

87
    initializer "active_record.check_schema_cache_dump" do
88 89 90
      if config.active_record.delete(:use_schema_cache_dump)
        config.after_initialize do |app|
          ActiveSupport.on_load(:active_record) do
K
Kir Shatrov 已提交
91
            filename = File.join(app.config.paths["db"].first, "schema_cache.yml")
92

93
            if File.file?(filename)
94
              current_version = ActiveRecord::Migrator.current_version
95

96 97
              next if current_version.nil?

K
Kir Shatrov 已提交
98
              cache = YAML.load(File.read(filename))
99
              if cache.version == current_version
100 101
                connection.schema_cache = cache
                connection_pool.schema_cache = cache.dup
102
              else
103
                warn "Ignoring db/schema_cache.yml because it has expired. The current schema version is #{current_version}, but the one in the cache is #{cache.version}."
104 105 106 107 108 109 110
              end
            end
          end
        end
      end
    end

111 112 113
    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
114
          require "active_record/relation/record_fetch_warning"
115 116 117 118
        end
      end
    end

119
    initializer "active_record.set_configs" do |app|
120
      ActiveSupport.on_load(:active_record) do
121 122 123
        configs = app.config.active_record.dup
        configs.delete(:sqlite3)
        configs.each do |k, v|
124 125
          send "#{k}=", v
        end
126 127 128 129 130
      end
    end

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

135 136 137 138 139
        begin
          establish_connection
        rescue ActiveRecord::NoDatabaseError
          warn <<-end_warning
Oops - You have a database configured, but it doesn't exist yet!
140

141 142 143
Here's how to get started:

  1. Configure your database in config/database.yml.
144 145
  2. Run `bin/rails db:create` to create the database.
  3. Run `bin/rails db:setup` to load your database schema.
146 147 148
end_warning
          raise
        end
149
      end
150 151
    end

152
    # Expose database runtime to controller for logging.
V
Vipul A M 已提交
153
    initializer "active_record.log_runtime" do
154
      require "active_record/railties/controller_runtime"
155
      ActiveSupport.on_load(:action_controller) do
156 157
        include ActiveRecord::Railties::ControllerRuntime
      end
158 159
    end

160 161 162 163 164 165 166 167
    initializer "active_record.collection_cache_association_loading" do
      require "active_record/railties/collection_cache_association_loading"
      ActiveSupport.on_load(:action_view) do
        ActionView::PartialRenderer.prepend(ActiveRecord::Railties::CollectionCacheAssociationLoading)
      end
    end


168
    initializer "active_record.set_reloader_hooks" do
J
Jon Leighton 已提交
169
      ActiveSupport.on_load(:active_record) do
170
        ActiveSupport::Reloader.before_class_unload do
171 172
          if ActiveRecord::Base.connected?
            ActiveRecord::Base.clear_cache!
173
            ActiveRecord::Base.clear_reloadable_connections!
174
          end
175
        end
176 177 178
      end
    end

179 180 181 182 183 184
    initializer "active_record.set_executor_hooks" do
      ActiveSupport.on_load(:active_record) do
        ActiveRecord::QueryCache.install_executor_hooks
      end
    end

185
    initializer "active_record.add_watchable_files" do |app|
186 187
      path = app.paths["db"].first
      config.watchable_files.concat ["#{path}/schema.rb", "#{path}/structure.sql"]
188
    end
189 190 191 192

    initializer "active_record.clear_active_connections" do
      config.after_initialize do
        ActiveSupport.on_load(:active_record) do
M
Matthew Draper 已提交
193 194 195 196 197 198 199 200
          # Ideally the application doesn't connect to the database during boot,
          # but sometimes it does. In case it did, we want to empty out the
          # connection pools so that a non-database-using process (e.g. a master
          # process in a forking server model) doesn't retain a needless
          # connection. If it was needed, the incremental cost of reestablishing
          # this connection is trivial: the rest of the pool would need to be
          # populated anyway.

201
          clear_active_connections!
M
Matthew Draper 已提交
202
          flush_idle_connections!
203 204 205
        end
      end
    end
206 207 208 209

    initializer "active_record.check_represent_sqlite3_boolean_as_integer" do
      config.after_initialize do
        ActiveSupport.on_load(:active_record_sqlite3adapter) do
210 211 212 213 214
          represent_boolean_as_integer = Rails.application.config.active_record.sqlite3.delete(:represent_boolean_as_integer)
          unless represent_boolean_as_integer.nil?
            ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer = represent_boolean_as_integer
          end

215 216 217 218 219 220 221 222 223
          unless ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer
            ActiveSupport::Deprecation.warn <<-MSG
Leaving `ActiveRecord::ConnectionAdapters::SQLite3Adapter.represent_boolean_as_integer`
set to false is deprecated. SQLite databases have used 't' and 'f' to serialize
boolean values and must have old data converted to 1 and 0 (its native boolean
serialization) before setting this flag to true. Conversion can be accomplished
by setting up a rake task which runs

  ExampleModel.where("boolean_column = 't'").update_all(boolean_column: 1)
224
  ExampleModel.where("boolean_column = 'f'").update_all(boolean_column: 0)
225 226 227 228

for all models and all boolean columns, after which the flag must be set to
true by adding the following to your application.rb file:

229
  Rails.application.config.active_record.sqlite3.represent_boolean_as_integer = true
230 231 232 233 234
MSG
          end
        end
      end
    end
235
  end
236
end