aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/railtie.rb
Commit message (Collapse)AuthorAgeFilesLines
* Expose foreign key name ignore pattern in configurationDavid Stosik2018-03-191-0/+1
| | | | | | | | | | | | | | | | | | | | | | | | | | | When dumping the database schema, Rails will dump foreign key names only if those names were not generate by Rails. Currently this is determined by checking if the foreign key name is `fk_rails_` followed by a 10-character hash. At [Cookpad](https://github.com/cookpad), we use [Departure](https://github.com/departurerb/departure) (Percona's pt-online-schema-change runner for ActiveRecord migrations) to run migrations. Often, `pt-osc` will make a copy of a table in order to run a long migration without blocking it. In this copy process, foreign keys are copied too, but [their name is prefixed with an underscore to prevent name collision ](https://www.percona.com/doc/percona-toolkit/LATEST/pt-online-schema-change.html#cmdoption-pt-online-schema-change-alter-foreign-keys-method). In the process described above, we often end up with a development database that contains foreign keys which name starts with `_fk_rails_`. That name does not match the ignore pattern, so next time Rails dumps the database schema (eg. when running `rake db:migrate`), our `db/schema.rb` file ends up containing those unwanted foreign key names. This also produces an unwanted git diff that we'd prefer not to commit. In this PR, I'd like to suggest a way to expose the foreign key name ignore pattern to the Rails configuration, so that individual projects can decide on a different pattern of foreign keys that will not get their names dumped in `schema.rb`.
* :scissors:Rafael Mendonça França2018-03-161-1/+0
| | | | [ci skip]
* Only preload misses on multifetch cacheLachlan Sylvester2018-03-061-0/+8
|
* Merge pull request #31690 from olivierlacan/no-verbose-query-logs-in-consoleRafael França2018-01-241-0/+1
|\ | | | | Only enable verbose_query_logs in Rails server
| * Disable verbose_query_logs in Rails ConsoleOlivier Lacan2018-01-231-0/+1
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Should fix #31688 unless someone can point me to a better way to achieve this goal. Essentially David's point was that verbose query logging when enabled in Rails console tends to make things very noisy. That's especially true if we display absolute paths to callsites which sadly is still the case when we detect a caller that isn't part of the Rails application — think gems. Discussed this with both @matthewd and @rafaelfranca and went back and forth between enabling if defined?(Rails::Server) or this implementation and this one makes more sense for now. Long term I think it'll make sense to let people override this default disabling in Rails Console because they might want to use the feature but for now it feels like the correct default behavior.
* | Refactor migration to move migrations paths to connectioneileencodes2018-01-181-0/+1
|/ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Rails has some support for multiple databases but it can be hard to handle migrations with those. The easiest way to implement multiple databases is to contain migrations into their own folder ("db/migrate" for the primary db and "db/seconddb_migrate" for the second db). Without this you would need to write code that allowed you to switch connections in migrations. I can tell you from experience that is not a fun way to implement multiple databases. This refactoring is a pre-requisite for implementing other features related to parallel testing and improved handling for multiple databases. The refactoring here moves the class methods from the `Migrator` class into it's own new class `MigrationContext`. The goal was to move the `migrations_paths` method off of the `Migrator` class and onto the connection. This allows users to do the following in their `database.yml`: ``` development: adapter: mysql2 username: root password: development_seconddb: adapter: mysql2 username: root password: migrations_paths: "db/second_db_migrate" ``` Migrations for the `seconddb` can now be store in the `db/second_db_migrate` directory. Migrations for the primary database are stored in `db/migrate`". The refactoring here drastically reduces the internal API for migrations since we don't need to pass `migrations_paths` around to every single method. Additionally this change does not require any Rails applications to make changes unless they want to use the new public API. All of the class methods from the `Migrator` class were `nodoc`'d except for the `migrations_paths` and `migrations_path` getter/setters respectively.
* Make `Migrator.current_version` work without a current databaseyuuji.yaginuma2017-12-031-2/+5
| | | | | | | This is necessary in order to make the processing dependent on `Migrator.current_version` work even without database. Context: https://github.com/rails/rails/pull/31135#issuecomment-348404326
* Flush idle database connectionsMatthew Draper2017-11-261-0/+9
|
* [Active Record] require => require_relativeAkira Matsuda2017-10-211-5/+5
| | | | This basically reverts 9d4f79d3d394edb74fa2192e5d9ad7b09ce50c6d
* Use frozen-string-literal in ActiveRecordKir Shatrov2017-07-191-0/+2
|
* Set `represent_boolean_as_integer` via `configuration`yuuji.yaginuma2017-07-161-2/+12
|
* Fix boolean column migration scriptyuuji.yaginuma2017-07-131-1/+1
|
* Change sqlite3 boolean serialization to use 1 and 0Lisa Ugray2017-07-111-0/+24
| | | | | | | | | | | | | | | | | | | | Abstract boolean serialization has been using 't' and 'f', with MySQL overriding that to use 1 and 0. This has the advantage that SQLite natively recognizes 1 and 0 as true and false, but does not natively recognize 't' and 'f'. This change in serialization requires a migration of stored boolean data for SQLite databases, so it's implemented behind a configuration flag whose default false value is deprecated. The flag itself can be deprecated in a future version of Rails. While loaded models will give the correct result for boolean columns without migrating old data, where() clauses will interact incorrectly with old data. While working in this area, also change the abstract adapter to use `"TRUE"` and `"FALSE"` as quoted values and `true` and `false` for unquoted. These are supported by PostreSQL, and MySQL remains overriden.
* [Active Record] require => require_relativeAkira Matsuda2017-07-011-5/+5
|
* Clear active connections after initializationEugene Kenny2017-02-171-0/+8
| | | | | | | | | | | | | Any connections that were checked out during initialization should be checked back in before the first request is processed, for two reasons: - Returning the connection to the pool allows it to be health checked before it's used again. If the connection dies before the first request arrives, the health check will replace it with a new one. - If the thread that initialized Rails is not the same thread that will be performing work, checking in the connection will allow it to be reused instead of being stuck to the initialization thread forever.
* `self.` is not needed when calling its own instance methodAkira Matsuda2017-01-051-2/+2
| | | | Actually, private methods cannot be called with `self.`, so it's not just redundant, it's a bad habit in Ruby
* Use YAML to serialize schema cacheKir Shatrov2016-11-271-3/+3
|
* Add more rubocop rules about whitespacesRafael Mendonça França2016-10-291-1/+1
|
* Add `Style/EmptyLines` in `.rubocop.yml` and remove extra empty linesRyuta Kamizono2016-08-071-1/+0
|
* modernizes hash syntax in activerecordXavier Noria2016-08-061-2/+2
|
* applies new string literal convention in activerecord/libXavier Noria2016-08-061-7/+7
| | | | | The current code base is not uniform. After some discussion, we have chosen to go with double quotes by default.
* rails -> Rails [ci skip]Santosh Wadghule2016-07-121-1/+1
|
* Revert "Ensure `config.active_record.time_zone_aware_types` is always set"Rafael Mendonça França2016-03-241-1/+0
| | | | | | | This reverts commit 43ccebc1db072ba0c96a67de0b3db78fd8fd0973. This is not fixing the configuration problem since we are assigning to the ActiveRecord::Base not the configuration. See #24303.
* Publish AS::Executor and AS::Reloader APIsMatthew Draper2016-03-021-10/+8
| | | | | | These should allow external code to run blocks of user code to do "work", at a similar unit size to a web request, without needing to get intimate with ActionDipatch.
* make rake proxy work in rails enginesyuuji.yaginuma2016-01-311-1/+1
|
* Ensure `config.active_record.time_zone_aware_types` is always setSean Griffin2016-01-071-0/+1
| | | | | | | | While the option on `ActiveRecord::Base` is always around, we need to explicitly set it on the config object. Otherwise the recommended configuration change results in an error. Fixes #22839
* [close #22917] Don't output to `STDOUT` twiceschneems2016-01-061-2/+4
| | | | | | | | | | | | | | When `rails console` or `rails server` are used along with a logger set to output to `STDOUT` then the contents will show up twice. This happens because the logger is extended with `ActiveSupportLogger.broadcast` with a destination of STDOUT even if it is already outputting to `STDOUT`. Previously PR #22592 attempted to fix this issue, but it ended up causing NoMethodErrors. A better approach than relying on adding a method and flow control is to inspect the log destination directly. For this `ActiveSupport::Logger.logger_outputs_to?` was introduced ```ruby logger = Logger.new(STDOUT) ActiveSupport::Logger.logger_outputs_to?(logger, STDOUT) # => true ``` To accomplish this we must look inside of an instance variable of standard lib's Logger `@logdev`. There is a related Ruby proposal to expose this method in a standard way: https://bugs.ruby-lang.org/issues/11955
* Refer to rails command instead of rake in a bunch of placesDavid Heinemeier Hansson2015-12-181-2/+2
| | | | Still more to do. Please assist!
* Remove unused block argumentamitkumarsuroliya2015-10-061-1/+1
|
* Fix middleware deprecation message. Related to #21172.Jon Atack2015-08-141-1/+1
|
* Reference actual classesMiles Starkenburg2015-08-081-5/+5
|
* Merge pull request #20516 from kares/patch-2Matthew Draper2015-06-121-1/+1
| | | | change AR clear order in ActionDisplatch::Reloader hook
* Apply schema cache dump when creating connectionsEugene Kenny2015-04-291-0/+1
| | | | | | | | | | | | | | | The `db:schema:cache:dump` rake task dumps the database schema structure to `db/schema_cache.dump`. If this file is present, the schema details are loaded into the currently checked out connection by a railtie while Rails is booting, to avoid having to query the database for its schema. The schema cache dump is only applied to the initial connection used to boot the application though; other connections from the same pool are created with an empty schema cache, and still have to load the structure of each table directly from the database. With this change, a copy of the schema cache is associated with the connection pool and applied to connections as they are created.
* Add `config.active_record.warn_on_records_fetched_greater_than` optionJason Nochlin2015-03-251-0/+8
| | | | | | | | | When set to an integer, a warning will be logged whenever a result set larger than the specified size is returned by a query. Fixes #16463 The warning is outputed a module which is prepended in an initializer, so there will be no performance impact if `config.active_record.warn_on_records_fetched_greater_than` is not set.
* Revert "Merge pull request #15476 from JacobEvelyn/master"Jeremy Kemper2015-03-111-3/+0
| | | | | | | | | | | | | | | | This introduces undesirable `Rails.logger` formatters (such as the syslog formatter) onto a `Logger.new(STDERR)` for the console. The production logger may be going elsewhere than standard io, so we can't presume to reuse its formatter. With syslog, this causes missing newlines in the console, so irb prompts start at the end of the last log message. We can work to expose the console formatter in another way to address the original issue. This reverts commit 026ce5ddf11c4cda0aae7f33a9266e54117db318, reversing changes made to 6f0a69c5899ebdc892e2aa23e68e2604fa70fb73.
* Merge pull request #15476 from JacobEvelyn/masterRafael Mendonça França2015-02-251-0/+3
|\ | | | | | | Use logger environment settings in Rails console.
| * Use logger environment settings in Rails console.Jacob Evelyn2014-06-021-0/+3
| |
* | do not trigger AR lazy load hook before initializers ran.Yves Senn2014-11-251-2/+0
|/ | | | | | | | | | | | | [Rafael Mendonça França & Yves Senn] This require caused the `active_record.set_configs` initializer to run immediately, before `config/initializers`. This means that setting any configuration on `Rails.application.config.active_record` inside of an initializer had no effects when rails was loaded through `rake`. Introduced by #6518 /cc @rafaelfranca
* Clarify 'database does not exist' message and implementation.Jeremy Kemper2014-04-011-9/+14
| | | | | | | | | | | * Clarify what the situation is and what to do. * Advise loading schema using `rake db:setup` instead of migrating. * Use a rescue in the initializer rather than extending the error message in-place. * Preserve the original backtrace of other errors by using `raise` rather than raising again with `raise error`. References 0ec45cd15d0a2f5aebc75e23d841b6c12f3ba763
* Ensure Active Record connection consistencyschneems2014-01-091-14/+2
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Currently Active Record can be configured via the environment variable `DATABASE_URL` or by manually injecting a hash of values which is what Rails does, reading in `database.yml` and setting Active Record appropriately. Active Record expects to be able to use `DATABASE_URL` without the use of Rails, and we cannot rip out this functionality without deprecating. This presents a problem though when both config is set, and a `DATABASE_URL` is present. Currently the `DATABASE_URL` should "win" and none of the values in `database.yml` are used. This is somewhat unexpected to me if I were to set values such as `pool` in the `production:` group of `database.yml` they are ignored. There are many ways that active record initiates a connection today: - Stand Alone (without rails) - `rake db:<tasks>` - ActiveRecord.establish_connection - With Rails - `rake db:<tasks>` - `rails <server> | <console>` - `rails dbconsole` We should make all of these behave exactly the same way. The best way to do this is to put all of this logic in one place so it is guaranteed to be used. Here is my prosed matrix of how this behavior should work: ``` No database.yml No DATABASE_URL => Error ``` ``` database.yml present No DATABASE_URL => Use database.yml configuration ``` ``` No database.yml DATABASE_URL present => use DATABASE_URL configuration ``` ``` database.yml present DATABASE_URL present => Merged into `url` sub key. If both specify `url` sub key, the `database.yml` `url` sub key "wins". If other paramaters `adapter` or `database` are specified in YAML, they are discarded as the `url` sub key "wins". ``` ### Implementation Current implementation uses `ActiveRecord::Base.configurations` to resolve and merge all connection information before returning. This is achieved through a utility class: `ActiveRecord::ConnectionHandling::MergeAndResolveDefaultUrlConfig`. To understand the exact behavior of this class, it is best to review the behavior in activerecord/test/cases/connection_adapters/connection_handler_test.rb though it should match the above proposal.
* Automatically maintain test database schemaJon Leighton2014-01-021-8/+1
| | | | | | | | | | | | | | * Move check from generated helper to test_help.rb, so that all applications can benefit * Rather than just raising when the test schema has pending migrations, try to load in the schema and only raise if there are pending migrations afterwards * Opt out of the check by setting config.active_record.maintain_test_schema = false * Deprecate db:test:* tasks. The test helper is now fully responsible for maintaining the test schema, so we don't need rake tasks for this. This is also a speed improvement since we're no longer reloading the test database on every call to "rake test".
* Avoid getting redefined method warningŁukasz Strzałkowski2013-12-251-0/+1
| | | | | | | Warning: ~/projects/rails/activerecord/lib/active_record/railtie.rb:140: warning: method redefined; discarding old extend_message ~/projects/rails/activerecord/lib/active_record/errors.rb:104: warning: previous definition of extend_message was here
* Only build a ConnectionSpecification if requiredJosé Valim2013-12-241-1/+1
|
* Fix build failures related to the new ENV options in ymlJosé Valim2013-12-241-1/+1
|
* Guarantee the connection resolver handles string valuesJosé Valim2013-12-231-1/+14
| | | | | | | | | This commit also cleans up the rake tasks that were checking for DATABASE_URL in different places. In fact, it would be nice to deprecate DATABASE_URL usage in the long term, considering the direction we are moving of allowing those in .yml files.
* Tell how to Create a Database in Error Messageschneems2013-12-231-0/+8
| | | | | | | | | | | | | | | | Currently if you attempt to use a database that does not exist you get an error: ``` PG::ConnectionBad FATAL: database "db_error" does not exist ``` The solution is easy, create and migrate your database however new developers may not know these commands by memory. Instead of requiring the developer to search for a solution, tell them how to fix the problem in the error message: ``` ActiveRecord::NoDatabase: FATAL: database "db_error" does not exist Run `$ bin/rake db:create db:migrate` to create your database ``` Active Record should not know about `rake db:migrate` so this additional information needs to come from the railtie. Potential alternative implementation suggestions are welcome.
* let the sqlite task run without railsDamien Mathieu2013-08-071-0/+1
|
* Remove deprecation messages about protected_attributes and rails-observersCarlos Antonio da Silva2013-07-011-39/+0
|
* remove auto-explain-config deprecation warningYves Senn2013-07-011-11/+0
|
* Setup env and seed_loaded for DatabaseTasks outside load_configPiotr Sarnacki2013-06-231-2/+3
| | | | Those vars can be used in tasks, which not call load_config.