railtie.rb 7.6 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_relative "railties/console_sandbox" if app.sandbox?
      require_relative "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 63
    end

V
Vipul A M 已提交
64
    runner do
65
      require_relative "base"
66 67
    end

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

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

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

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

92
            if File.file?(filename)
K
Kir Shatrov 已提交
93
              cache = YAML.load(File.read(filename))
94
              if cache.version == ActiveRecord::Migrator.current_version
95 96
                connection.schema_cache = cache
                connection_pool.schema_cache = cache.dup
97
              else
K
Kir Shatrov 已提交
98
                warn "Ignoring db/schema_cache.yml because it has expired. The current schema version is #{ActiveRecord::Migrator.current_version}, but the one in the cache is #{cache.version}."
99 100 101 102 103 104 105
              end
            end
          end
        end
      end
    end

106 107 108
    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
109
          require_relative "relation/record_fetch_warning"
110 111 112 113
        end
      end
    end

114
    initializer "active_record.set_configs" do |app|
115
      ActiveSupport.on_load(:active_record) do
116 117 118
        configs = app.config.active_record.dup
        configs.delete(:sqlite3)
        configs.each do |k, v|
119 120
          send "#{k}=", v
        end
121 122 123 124 125
      end
    end

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

130 131 132 133 134
        begin
          establish_connection
        rescue ActiveRecord::NoDatabaseError
          warn <<-end_warning
Oops - You have a database configured, but it doesn't exist yet!
135

136 137 138
Here's how to get started:

  1. Configure your database in config/database.yml.
139 140
  2. Run `bin/rails db:create` to create the database.
  3. Run `bin/rails db:setup` to load your database schema.
141 142 143
end_warning
          raise
        end
144
      end
145 146
    end

147
    # Expose database runtime to controller for logging.
V
Vipul A M 已提交
148
    initializer "active_record.log_runtime" do
149
      require_relative "railties/controller_runtime"
150
      ActiveSupport.on_load(:action_controller) do
151 152
        include ActiveRecord::Railties::ControllerRuntime
      end
153 154
    end

155
    initializer "active_record.set_reloader_hooks" do
J
Jon Leighton 已提交
156
      ActiveSupport.on_load(:active_record) do
157
        ActiveSupport::Reloader.before_class_unload do
158 159
          if ActiveRecord::Base.connected?
            ActiveRecord::Base.clear_cache!
160
            ActiveRecord::Base.clear_reloadable_connections!
161
          end
162
        end
163 164 165
      end
    end

166 167 168 169 170 171
    initializer "active_record.set_executor_hooks" do
      ActiveSupport.on_load(:active_record) do
        ActiveRecord::QueryCache.install_executor_hooks
      end
    end

172
    initializer "active_record.add_watchable_files" do |app|
173 174
      path = app.paths["db"].first
      config.watchable_files.concat ["#{path}/schema.rb", "#{path}/structure.sql"]
175
    end
176 177 178 179 180 181 182 183

    initializer "active_record.clear_active_connections" do
      config.after_initialize do
        ActiveSupport.on_load(:active_record) do
          clear_active_connections!
        end
      end
    end
184 185 186 187

    initializer "active_record.check_represent_sqlite3_boolean_as_integer" do
      config.after_initialize do
        ActiveSupport.on_load(:active_record_sqlite3adapter) do
188 189 190 191 192
          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

193 194 195 196 197 198 199 200 201
          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)
202
  ExampleModel.where("boolean_column = 'f'").update_all(boolean_column: 0)
203 204 205 206

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:

207
  Rails.application.config.active_record.sqlite3.represent_boolean_as_integer = true
208 209 210 211 212
MSG
          end
        end
      end
    end
213
  end
214
end