Commit Graph

14399 Commits

Author SHA1 Message Date
Ryuta Kamizono 1aece76e25 Move all Arel constructions from uniqueness validator into connection adapter 2019-03-07 10:53:53 +09:00
willnet 6c797d6e03 [ci skip]Fix typo: constaint -> constraint 2019-03-07 10:42:22 +09:00
Samantha John 755112c7b1 Replace “can not” with “cannot”. 2019-03-06 16:35:52 -05:00
Eileen M. Uchitelle a2bc42f1e7
Merge pull request #35497 from eileencodes/parse-yaml-without-erb-for-rake-tasks
Load YAML for rake tasks without parsing ERB
2019-03-06 13:02:48 -05:00
Kasper Timm Hansen 1818c4e8b4
Add some whitespace for readability. 2019-03-06 16:29:22 +01:00
Kasper Timm Hansen ba795c9e4a
Handle blank inserts like update_all; raise upfront. 2019-03-06 16:19:53 +01:00
Ryuta Kamizono fd18b98dd9 Allow `remove_foreign_key` with both `to_table` and `options`
Foreign keys could be created to the same table.
So `remove_foreign_key :from_table, :to_table` is sometimes ambiguous.
This allows `remove_foreign_key` to remove the select one on the same
table with giving both `to_table` and `options`.
2019-03-06 23:45:08 +09:00
eileencodes 37d1429ab1 Load YAML for rake tasks without parsing ERB
This change adds a new method that loads the YAML for the database
config without parsing the ERB. This may seem odd but bear with me:

When we added the ability to have rake tasks for multiple databases we
started looping through the configurations to collect the namespaces so
we could do `rake db:create:my_second_db`. See #32274.

This caused a problem where if you had `Rails.config.max_threads` set in
your database.yml it will blow up because the environment that defines
`max_threads` isn't loaded during `rake -T`. See #35468.

We tried to fix this by adding the ability to just load the YAML and
ignore ERB all together but that caused a bug in GitHub's YAML loading
where if you used multi-line ERB the YAML was invalid. That led us to
reverting some changes in #33748.

After trying to resolve this a bunch of ways `@tenderlove` came up with
replacing the ERB values so that we don't need to load the environment
but we also can load the YAML.

This change adds a DummyCompiler for ERB that will replace all the
values so we can load the database yaml and create the rake tasks.
Nothing else uses this method so it's "safe".

DO NOT use this method in your application.

Fixes #35468
2019-03-06 08:59:27 -05:00
Abhay Nikam 664685680c [ci skip] Fix typo beacuse -> because 2019-03-06 07:49:26 +05:30
Ryuta Kamizono a67841eb61 Ensure `clear_cache!` clears the prepared statements cache
Since #23461, all adapters supports prepared statements, so that clears
the prepared statements cache is no longer database specific.

Actually, I struggled to identify the cause of random CI failure in
#23461, that was missing `@statements.clear` in `clear_cache!`.

This extracts `clear_cache!` to ensure the common concerns in the
abstract adapter.
2019-03-06 08:12:41 +09:00
Bob Lail 91ed21b304 Add insert_all to ActiveRecord models (#35077)
Adds a method to ActiveRecord allowing records to be inserted in bulk without instantiating ActiveRecord models. This method supports options for handling uniqueness violations by skipping duplicate records or overwriting them in an UPSERT operation.

ActiveRecord already supports bulk-update and bulk-destroy actions that execute SQL UPDATE and DELETE commands directly. It also supports bulk-read actions through `pluck`. It makes sense for it also to support bulk-creation.
2019-03-05 11:16:44 -08:00
Bogdan a8c0ebccbd Allow `truncate` for SQLite3 adapter and add `rails db:seed:replant` (#34779)
* Add `ActiveRecord::Base.connection.truncate` for SQLite3 adapter.

SQLite doesn't support `TRUNCATE TABLE`, but SQLite3 adapter can support
`ActiveRecord::Base.connection.truncate` by using `DELETE FROM`.

`DELETE` without `WHERE` uses "The Truncate Optimization",
see https://www.sqlite.org/lang_delete.html.

* Add `rails db:seed:replant` that truncates database tables and loads the seeds

Closes #34765
2019-03-04 14:57:38 -08:00
Ryuta Kamizono 9def05385f Deprecate mismatched collation comparison for uniquness validator
In MySQL, the default collation is case insensitive. Since the
uniqueness validator enforces case sensitive comparison by default, it
frequently causes mismatched collation issues (performance, weird
behavior, etc) to MySQL users.

https://grosser.it/2009/12/11/validates_uniqness_of-mysql-slow/
https://github.com/rails/rails/issues/1399
https://github.com/rails/rails/pull/13465
c1dddf8c7d
https://github.com/huginn/huginn/pull/1330#discussion_r55152573

I'd like to deprecate the implicit default enforcing since I frequently
experienced the problems in code reviews.

Note that this change has no effect to sqlite3, postgresql, and
oracle-enhanced adapters which are implemented as case sensitive by
default, only affect to mysql2 adapter (I can take a work if sqlserver
adapter will support Rails 6.0).
2019-03-04 21:00:03 +09:00
Abhay Nikam 82b0ff03b1 Fixed reselect throwing NoMethodError on ActiveRecord. 2019-03-03 22:25:10 +05:30
Ryuta Kamizono 6568d7da63
Merge pull request #35441 from kamipo/allow_from_with_index_hint
Relax table name detection in `from` to allow any extension like INDEX hint
2019-03-01 23:25:01 +09:00
Ryuta Kamizono c82705b15f
Merge pull request #35431 from kamipo/enable_sql_cache_on_find
Enable SQL statement cache for `find` on base class as with `find_by`
2019-03-01 22:45:57 +09:00
Ryuta Kamizono bff5e799c0 Relax table name detection in `from` to allow any extension like INDEX hint
#35360 allows table name qualified if `from` has original table name.
But that is still too strict. We have a valid use case that `from` with
INDEX hint (e.g. `from("comments USE INDEX (PRIMARY)")`).
So I've relaxed the table name detection in `from` to allow any
extension like INDEX hint.

Fixes #35359.
2019-03-01 22:41:46 +09:00
Andrew White 0c4bf982e8
Merge pull request #33611 from willianveiga/feature/reselect-method
Add reselect method
2019-03-01 08:33:01 +00:00
Ryuta Kamizono dda5501e80 Enable SQL statement cache for `find` on base class as with `find_by`
Related and follows d333d85254.
2019-03-01 16:28:32 +09:00
Mehmet Emin INAC f98bb46543
[ci skip] The `find` method coerces the given arguments to integer if the `primary key` is integer 2019-02-28 17:56:01 +01:00
Mehmet Emin INAC dedf7a2262
[ci skip] Fix the documentation of ActiveRecord::FinderMethods#find
It's mentioned everywhere as `ActiveRecord::RecordNotFound` so to be
coherent with the rest of the documentation I've applied it here.
Also doc was saying if the parameter is integer it coerces it which is
other way around.
2019-02-28 11:09:35 +01:00
Ryuta Kamizono 06eabecfc0 Refactor `generated_relation_methods` to remove duplicated code on `ClassSpecificRelation` 2019-02-28 01:32:57 +09:00
Ryuta Kamizono 634953af94 Allow returning nil for `default_scope` 2019-02-28 00:24:23 +09:00
Rafael Mendonça França 572dcdd7e8
Fix preload with nested associations
When the middle association doesn't have any records and the inner
association is not an empty scope the owner will be `nil` so we can't
try to reset the inverse association.
2019-02-26 18:07:13 -05:00
David Heinemeier Hansson 55a7051a5a
Add negative scopes for all enum values (#35381)
Add negative scopes for all enum values
2019-02-26 12:47:27 -08:00
Ryuta Kamizono d333d85254 Don't cache `find_by` statements on STI subclasses
Caching `find_by` statements on STI subclasses is unsafe, since
`type IN (?,?,?,?)` part is dynamic, and we don't have SQL statements
cache invalidation when a STI subclass is created or removed for now.
2019-02-27 03:40:53 +09:00
jvillarejo fa2c61fc63 fixes different `count` calculation when using `size` manual `select` with DISTINCT
When using `select` with `'DISTINCT( ... )'` if you use method `size` on a non loaded relation it overrides the column selected by passing `:all` so it returns different value than count.

This fixes #35214
2019-02-26 12:21:14 -03:00
Rafael Mendonça França 5e6e505083
Preparing for 6.0.0.beta2 release 2019-02-25 17:45:04 -05:00
Aaron Patterson ec30b84267
Merge pull request #35402 from alimi/update-ar-read-regex
Support read queries with leading characters while preventing writes
2019-02-25 11:33:38 -08:00
Ryuta Kamizono 67732efcb6 Refactor `type_to_sql` to handle converting `limit` to `size` in itself
Also, improving an argument error message for `limit`, extracting around
`type_to_sql` code into schema statements, and more exercise tests.
2019-02-26 02:34:53 +09:00
Ryuta Kamizono 66b4ddd335 Fix prepared statements caching to be enabled even when query caching is enabled
Related cbcdecd, 2a56b2d.

This is a regression caused by cbcdecd.

If query caching is enabled, prepared statement handles are never
re-used, since we missed that a query is preprocessed when query caching
is enabled, but doesn't keep the `preparable` flag.

We should care about that case.
2019-02-26 00:30:26 +09:00
Ali Ibrahim b7eeb142af Update READ_QUERY regex
* The READ_QUERY regex would consider reads to be writes if they started with
    spaces or parens. For example, a UNION query might have parens around each
    SELECT - (SELECT ...) UNION (SELECT ...).
  * It will now correctly treat these queries as reads.
2019-02-25 10:19:43 -05:00
Ryuta Kamizono 66d40abff5
Merge pull request #35352 from kamipo/update_all_doesnt_care_optimistic_locking
Ensure `update_all` series doesn't care optimistic locking
2019-02-25 20:49:07 +09:00
Ryuta Kamizono 1d8fad6f90 Ensure `update_all` series cares about optimistic locking
Incrementing the lock version invalidates any other process's optimistic
lock, which is the desired outcome: the record no longer looks the same
as it did when they loaded it.
2019-02-25 20:14:56 +09:00
Shivam Jain 8cabcccf42 minor grammar fix [ci skip] 2019-02-24 01:03:10 +05:30
Ryuta Kamizono 6e599ee099 Fix `pluck` and `select` with `from` if `from` has original table name
This is caused by 0ee96d1.

Since #18744, `select` columns doesn't be qualified by table name if
using `from`. 0ee96d1 follows that for `pluck` as well.

But people depends that `pluck` columns are qualified even if using
`from`.

So I've fixed that to be qualified if `from` has the original table name
to keep the behavior as much as before.

Fixes #35359.
2019-02-22 06:14:33 +09:00
Ryuta Kamizono 3b6602aa7a Should not pass extra args to `_update_record`
The argument of `_update_record` and `_create_record` is
`attribute_names`, that is reserved for overriding by partial writes
attribute names.

67e20d1d48/activerecord/lib/active_record/persistence.rb (L719)
67e20d1d48/activerecord/lib/active_record/persistence.rb (L737)
67e20d1d48/activerecord/lib/active_record/attribute_methods/dirty.rb (L171)
67e20d1d48/activerecord/lib/active_record/attribute_methods/dirty.rb (L177)

The reason that no failing with extra args is that `Timestamp` module
which is most outside module of the `_update_record` discards the extra
args.

67e20d1d48/activerecord/lib/active_record/timestamp.rb (L104)

But that looks odd dependency. It should not be passed extra args,
should only be passed attribute names.
2019-02-21 21:59:31 +09:00
Ryuta Kamizono b57ca840a6 Address "warning: in `column': the last argument was passed as a single Hash" 2019-02-21 17:41:39 +09:00
Ryuta Kamizono 6cb176cddf Extract `default_uniqueness_comparison` to ease to handle mismatched collation issues
In MySQL, the default collation is case insensitive. Since the
uniqueness validator enforces case sensitive comparison by default, it
frequently causes mismatched collation issues (performance, weird
behavior, etc) to MySQL users.

https://grosser.it/2009/12/11/validates_uniqness_of-mysql-slow/
https://github.com/rails/rails/issues/1399
https://github.com/rails/rails/pull/13465
c1dddf8c7d
https://github.com/huginn/huginn/pull/1330#discussion_r55152573

This extracts `default_uniqueness_comparison` to ease to handle the
mismatched collation issues on the connection.
2019-02-21 15:59:26 +09:00
soartec-lab 0fecd26625 Fix lint `ShadowingOuterLocalVariable`
Revert "Fix lint `ShadowingOuterLocalVariable`"

This reverts commit 38bd45a48992b500478a82d56d31468a322937a8.

Change of variable name

Fix lint `ShadowingOuterLocalVariable`
2019-02-21 14:43:06 +09:00
Ryuta Kamizono dfa857ef25
Merge pull request #35263 from hatch-carl/reduce-postgres-uuid-allocations
Reduce unused allocations when casting UUIDs for Postgres
2019-02-21 01:59:43 +09:00
Carl Thuringer 6735a0719d
Reduce unused allocations when casting UUIDs for Postgres
Using the subscript method `#[]` on a string has several overloads and
rather complex implementation. One of the overloads is the capability to
accept a regular expression and then run a match, then return the
receiver (if it matched) or one of the groups from the MatchData.

The function of the `UUID#cast` method is to cast a UUID to a type and
format acceptable by postgres. Naturally UUIDs are supposed to be
string and of a certain format, but it had been determined that it was
not ideal for the framework to send just any old string to Postgres and
allow the engine to complain when "foobar" or "" was sent, being
obviously of the wrong format for a valid UUID. Therefore this code was
written to facilitate the checking, and if it were not of the correct
format, a `nil` would be returned as is conventional in Rails.

Now, the subscript method will allocate one or more strings on a match
and return one of them, based on the index parameter. However, there
is no need for a new string, as a UUID of the correct format is already
such, and so long as the format was verified then the string supplied is
adequate for consumption by the database.

The subscript method also creates a MatchData object which will never be
used, and so must eventually be garbage collected.

Garbage collection indeed. This innocuous method tends to be called
quite a lot, for example if the primary key of a table is a uuid, then
this method will be called. If the foreign key of a relation is a UUID,
once again this method is called. If that foreign key is belonging to
a has_many relationship with dozens of objects, then again dozens of
UUIDs shall be cast to a dup of themselves, and spawn dozens of
MatchData objects, and so on.

So, for users that:
* Use UUIDs as primary keys
* Use Postgres
* Operate on collections of objects

This accomplishes a significant savings in total allocations, and may
save many garbage collections.
2019-02-20 10:11:35 -06:00
Ryuta Kamizono ceed0aa2e0
Merge pull request #35327 from abhaynikam/use-delete-by-and-destroy-by-method
Replaced usage of where.delete/destroy_all with delete/destroy_by
2019-02-20 22:27:22 +09:00
Ryuta Kamizono df2ebf9b59
Merge pull request #35247 from bogdan/fix-source-reflection-reset-code
Fix reset of the source association when through association is loaded
2019-02-20 21:24:38 +09:00
Ryuta Kamizono fd919ec881 PostgreSQL: Support endless range values for range types 2019-02-20 21:14:24 +09:00
Bogdan Gusiev bd4eff2f99 Fix reset of the source association when through association is loaded
The special case happens when through association has a custom scope
that is applied to the source association when loading.
In this case, the soucre association would need to be reset after
main association is loaded. See tests.

The special case exists when a through association has
2019-02-20 13:48:51 +02:00
Abhay Nikam 11c34d8ef4 Replaced usage of where.delete/destroy_all with delete/destroy_by 2019-02-20 09:19:19 +05:30
Ryuta Kamizono 64ef5e2f9e Merge pull request #35316 from abhaynikam/35304-add-delete_by_and_destroy_by
Introduce delete_by and destroy_by methods to ActiveRecord::Relation
2019-02-19 21:52:49 +09:00
Abhay Nikam 5c8d4c3466 Introduce delete_by and destroy_by methods to ActiveRecord::Relation 2019-02-19 16:57:49 +05:30
Ryuta Kamizono b09d8f6bb3 Don't allow `where` with invalid value matches to nil values
That is considered as silently leaking information.
If type casting doesn't return any actual value, it should not be
matched to any record.

Fixes #33624.
Closes #33946.
2019-02-18 16:57:10 +09:00
Ryuta Kamizono 6a1a1e66ea Use placeholder for `type_condition` predicate
Before:

```
SELECT "comments".* FROM "comments" WHERE "comments"."type" IN ('VerySpecialComment') AND "comments"."post_id" = ? LIMIT ?  [["post_id", 4], ["LIMIT", 1]]
```

After:

```
SELECT "comments".* FROM "comments" WHERE "comments"."type" = ? AND "comments"."post_id" = ? LIMIT ?  [["type", "VerySpecialComment"], ["post_id", 4], ["LIMIT", 1]]
```
2019-02-18 01:39:06 +09:00
Ryuta Kamizono 49bcb008cb Fix eager loading polymorphic association with mixed table conditions
This fixes a bug that the `foreign_key` and the `foreign_type` are
separated as different table conditions if a polymorphic association has
a scope that joins another tables.
2019-02-18 00:41:43 +09:00
Ryuta Kamizono 5ca19efafe
Merge pull request #35274 from AlexBrodianoi/fix_does_not_support_reverse
Raise ActiveRecord::IrreversibleOrderError if nulls first/last is not a single ordering argument.
2019-02-17 12:39:44 +09:00
Finn Young db930ec0fd Raise ActiveRecord::IrreversibleOrderError if nulls first/last is not a single ordering argument. 2019-02-17 00:41:30 +00:00
Ryuta Kamizono 311f001167 Fix `order` with custom attributes
This follows up 0ee96d13de.
2019-02-17 02:44:37 +09:00
Ryuta Kamizono 3ac195c534 Fix the regex that extract mismatched foreign key information
The CI failure for `test_errors_for_bigint_fks_on_integer_pk_table` is
due to the poor regex that extract all ``` `(\w+)` ``` like parts from
the message (`:foreign_key` should be `"old_car_id"`, but `"engines"`):

https://travis-ci.org/rails/rails/jobs/494123455#L1703

I've improved the regex more strictly and have more exercised mismatched
foreign key tests.

Fixes #35294
2019-02-17 00:53:26 +09:00
Ryuta Kamizono fed7888c83 Merge pull request #35297 from yhara/fix-ar-connection-handler-leak
Fix possible memory leak of ConnectionHandler
2019-02-16 23:11:27 +09:00
Yutaka HARA 20a7262790 Fix possible memory leak of ConnectionHandler
refs #35296
2019-02-16 22:31:15 +09:00
Ryuta Kamizono 6572175d4d Refactor `remove_foreign_key` to delete the foreign key before `alter_table` 2019-02-16 14:56:29 +09:00
Ryuta Kamizono b353391846 Merge pull request #35286 from matthewdunbar/master
Properly handle cached queries with too many bind parameters
2019-02-16 14:16:44 +09:00
Ryuta Kamizono 4c6171d605 Deprecate using class level querying methods if the receiver scope regarded as leaked
This deprecates using class level querying methods if the receiver scope
regarded as leaked, since #32380 and #35186 may cause that silently
leaking information when people upgrade the app.

We need deprecation first before making those.
2019-02-15 17:40:15 +09:00
Matthew Dunbar 795c0f8205 Properly handle cached queries with too many bind parameters 2019-02-14 23:25:44 -05:00
Ryuta Kamizono cdb8697b4a Revert "Merge pull request #35186 from kamipo/fix_leaking_scope_on_relation_create"
This reverts commit b67d5c6ded, reversing
changes made to 2e018361c7.

Reason: #35186 may cause that silently leaking information when people
upgrade the app.

We need deprecation first before making this.
2019-02-15 12:06:45 +09:00
Abhay Nikam 85efb7cfe6 Minor changes to deprecation warning message after 35242 2019-02-15 00:33:36 +05:30
Eileen M. Uchitelle 5f7180676b
Merge pull request #35242 from eileencodes/add-setter-and-deprecation-for-configurations-hashes
Add setter and deprecation for configurations hashes
2019-02-14 12:58:54 -05:00
eileencodes 06f9434342 Improve errors and handling of hashes for database configurations
In chat Sam Saffron asked how to use the setter now that configurations
is no longer a hash and you need to do AR::Base.configurations["test"]=.

Technically you can do `ActiveRecord::Base.configurations = { the hash
}` but I realized the old way throws an error and is unintuitive.

To aid in the transition from hashes to objects this PR makes a few
changes:

1) Re-adds a deprecated hash setter `[]=` that will add a new hash
to the configurations list OR replace an existing hash if that
environment is already present. This won't be supported in future Rails
versions but a good error is important.

2) Changed to throw deprecation warnings on the methods we decided to support
for hash conversion and raise on the methods we don't support.

3) Refactored the setter/getter hash deprecation warnings messages and
rewrote them.

Getters message:

```
DEPRECATION WARNING: `ActiveRecord::Base.configurations` no longer
returns a hash. Methods that act on the hash like `values` are
deprecated and will be removed in Rails 6.1. Use the `configs_for`
method to collect and iterate over the database configurations.
```

Setter message:

```
DEPRECATION WARNING: Setting `ActiveRecord::Base.configurations` with
`[]=` is deprecated. Use `ActiveRecord::Base.configurations=` directly
to set the configurations instead.
```

4) Rewrote the legacy configurations test file to test all the public
methods in the DatabaseConfigurations class.
2019-02-14 08:25:52 -05:00
Ryuta Kamizono 4f2a635661 Revert "Chaining named scope is no longer leaking to class level querying methods"
This reverts #32380, since this may cause that silently leaking
information when people upgrade the app.

We need deprecation first before making this.
2019-02-14 05:22:41 +09:00
Eileen M. Uchitelle be099cc13f
Merge pull request #35244 from palkan/fix/activerecord-database-uri-resolve
Fix database configurations building when DATABASE_URL present
2019-02-13 10:57:05 -05:00
Ryuta Kamizono 47e3bbeb90 Revert "Merge pull request #35127 from bogdan/counter-cache-loading"
This reverts commit eec3e28a1a, reversing
changes made to 5588fb4802.

Reason: Marking as loaded without actual loading is too greedy optimization.

See more context #35239.

Closes #35239.

[Edouard CHIN & Ryuta Kamizono]
2019-02-13 22:45:35 +09:00
utilum 87a5379b42 Ruby 2.7 warning: creating a Proc without a block
As of [Revision 66772](
https://bugs.ruby-lang.org/projects/ruby-trunk/repository/trunk/revisions/66772)
 `Proc.new` without giving a block emits `warning: tried to create Proc object without a block`.

This commit fixes cases where Rails test suit tickles this warning.

See CI logs:
https://travis-ci.org/rails/rails/jobs/487205819#L1161-L1190
https://travis-ci.org/rails/rails/jobs/487205821#L1154-1159
https://travis-ci.org/rails/rails/jobs/487205821#L1160-L1169
https://travis-ci.org/rails/rails/jobs/487205821#L1189
https://travis-ci.org/rails/rails/jobs/487254404#L1307-L1416
https://travis-ci.org/rails/rails/jobs/487254405#L1174-L1191
2019-02-13 02:11:21 +01:00
Vladimir Dementyev d9b261a340
Fix database configurations building when DATABASE_URL present 2019-02-12 17:00:17 -05:00
Ryuta Kamizono 7432e25187 Should respect attribute_types over column_types
Fixed the CI failure https://travis-ci.org/rails/rails/jobs/492291248#L1185-L1191.
2019-02-13 04:10:13 +09:00
Ryuta Kamizono 0ee96d13de Fix `pluck` and `select` with custom attributes
Currently custom attributes are always qualified by the table name in
the generated SQL wrongly even if the table doesn't have the named
column, it would cause an invalid SQL error.

Custom attributes should only be qualified if the table has the same
named column.
2019-02-13 02:47:46 +09:00
Ryuta Kamizono eb7c71bcd3 Avoid implicit delegation in the migration compatibility
The implicit delegation in the migration class is to be logged. It is
not intended in the migration compatibility, so it should be avoided.

Fixes #35224.
2019-02-12 07:18:40 +09:00
Gannon McGibbon 1bbf08bb49
Merge pull request #35196 from gmcgibbon/clarify_collection_proxy_docs
Clarify collection proxy docs
2019-02-11 10:29:46 -05:00
Ryuta Kamizono 93c2182836 Add `remove_foreign_key` for `change_table` 2019-02-11 23:46:07 +09:00
Ryuta Kamizono 713cee01a5 Fix typo a -> an, an -> a [ci skip] 2019-02-11 17:03:10 +09:00
Ryuta Kamizono da5843436b SQLite3: Implement `add_foreign_key` and `remove_foreign_key`
I implemented Foreign key create in `create_table` for SQLite3 at
#24743. This follows #24743 to implement `add_foreign_key` and
`remove_foreign_key`.
Unfortunately SQLite3 has one limitation that
`PRAGMA foreign_key_list(table-name)` doesn't have constraint name.
So we couldn't implement find/remove foreign key by name for now.

Fixes #35207.
Closes #31343.
2019-02-11 14:15:16 +09:00
Ryuta Kamizono d87afbf46f More exercise table name prefix and suffix tests 2019-02-11 13:55:06 +09:00
Ryuta Kamizono c83254db7a Merge pull request #35203 from chiastolite/add_column_without_column_names
Do not allow to add column without column name
2019-02-10 08:43:18 +09:00
Hiroyuki Morita 0914ea8477 Do not allow to add column without column name 2019-02-10 04:01:59 +09:00
Ryuta Kamizono c7721ea6b3 Refactor to extract defining column methods as `define_column_methods`
It makes to ease to handle all short-hand methods (e.g. validates
arguments etc).
2019-02-09 14:10:35 +09:00
Gannon McGibbon 7354d71f92 Clarify collection proxy docs
The docs for `ActiveRecord::Associations::CollectionProxy` describe
`ActiveRecord::Associations::Association`. I've moved them to
association and rewrote collection proxy's docs to be more applicable to
what the class actually does.`

[ci skip]
2019-02-08 11:11:19 -05:00
Ryuta Kamizono 5f9e05048d Refactor to just use `Association#target=` in `associate_records_to_owner`
`Association#target=` invokes `loaded!`, so we no longer need to call
the `loaded!` explicitly.

Since Preloader is private API, we don't guarantee that it behaves like
older version as long as using Preloader directly. But this refactoring
fortunately also fix the Preloader compatibility issue #35195.

Closes #35195.
2019-02-09 01:04:59 +09:00
Kasper Timm Hansen 216b8aa40f
Merge pull request #34618 from bogdanvlviv/fix-elapsed-time-calculations
Fix elapsed time calculations
2019-02-08 16:54:13 +01:00
Ryuta Kamizono 8cae8dcf54
Merge pull request #35193 from kamipo/fix_exists_with_distinct_and_offset
Fix `relation.exists?` with giving both `distinct` and `offset`
2019-02-08 23:48:21 +09:00
Ryuta Kamizono e133573c81
Merge pull request #35178 from bogdan/has-many-size
Bugfix has_many association #size when ids reader is cached and assoc…
2019-02-08 22:39:58 +09:00
bogdanvlviv dda9452314
Fix elapsed time calculations
I've found a few places in Rails code base where I think it makes sense
to calculate elapsed time more precisely by using
`Concurrent.monotonic_time`:

- Fix calculation of elapsed time in `ActiveSupport::Cache::MemoryStore#prune`
- Fix calculation of elapsed time in
  `ActiveRecord::ConnectionAdapters::ConnectionPool::Queue#wait_poll`
- Fix calculation of elapsed time in
  `ActiveRecord::ConnectionAdapters::ConnectionPool#attempt_to_checkout_all_existing_connections`
- Fix calculation of elapsed time in `ActiveRecord::ConnectionAdapters::Mysql2Adapter#explain`

See
https://docs.ruby-lang.org/en/2.5.0/Process.html#method-c-clock_gettime
https://blog.dnsimple.com/2018/03/elapsed-time-with-ruby-the-right-way

Related to 7c4542146f
2019-02-08 13:27:30 +00:00
Ryuta Kamizono 07dcd99a5a Fix `relation.exists?` with giving both `distinct` and `offset`
The `distinct` affects (reduces) rows of the result, so it is important
part when both `distinct` and `offset` are given.

Replacing SELECT clause to `1 AS one` and removing `distinct` and
`order` is just optimization for the `exists?`, we should not apply the
optimization for that case.

Fixes #35191.
2019-02-08 21:28:50 +09:00
Bogdan Gusiev 7f153e936a Bugfix has_many association #size when ids reader is cached and association is changed 2019-02-08 11:39:53 +02:00
Ryuta Kamizono 4cb1438b57 Refactor extracting `current_scope_restoring_block` into the scoping class
Relation is not best place to do this.
2019-02-08 11:12:08 +09:00
John Hawthorn 3302d2c2e6 Rename database_operations config to *_context 2019-02-07 15:41:43 -08:00
Eileen M. Uchitelle ac0dcbdc77
Merge pull request #35182 from jhawthorn/db-selection-refactor
Improve naming in DatabaseSelector
2019-02-07 18:27:26 -05:00
John Hawthorn a68bcde506 Rename database selector operations to context 2019-02-07 14:32:54 -08:00
Ryuta Kamizono 22360534ac Fix `relation.create` to avoid leaking scope to initialization block and callbacks
`relation.create` populates scope attributes to new record by `scoping`,
it is necessary to assign the scope attributes to the record and to find
STI subclass from the scope attributes.

But the effect of `scoping` is class global, it was caused undesired
behavior that pollute all class level querying methods in initialization
block and callbacks (`after_initialize`, `before_validation`,
`before_save`, etc), which are user provided code.

To avoid the leaking scope issue, restore the original current scope
before initialization block and callbacks are invoked.

Fixes #9894.
Fixes #17577.
Closes #31526.
2019-02-07 21:04:01 +09:00
Ryuta Kamizono 2e018361c7 Refactor around scoping
Don't use `false` as special value to skip to find inherited scope, we
could use `skip_inherited_scope = true`, and move `_scoping` back on
Relation.
2019-02-07 19:44:25 +09:00
John Hawthorn ed1f392ea6 Rename resolver ivar to operations in Resolver
We're already in the resolver, we call this class "operations" in the
middleware, so we should use the same naming here.
2019-02-06 11:57:30 -08:00
John Hawthorn 6aaf01385e Rename Session.build to Session.call
This is more consistent with Resolver, which has build called. This
allows using a Proc instead of a class, which could be nice if you need
to vary switching logic based on the request in a more ad-hoc way (ie.
check if it is an API request).
2019-02-06 11:55:53 -08:00
Yuya Tanaka 788eb51df3 Fix `CollectionProxy#concat` to return self by alias it to `#<<`
Formerly it was returning arguments (`records` array).
2019-02-06 15:01:48 +09:00
Aaron Patterson 9483cdee0a
Merge pull request #35171 from rails/speed-up-partials
Speed up partial rendering by caching "variable" calculation
2019-02-05 16:41:43 -08:00
Aaron Patterson 24b068bea1
Speed up partial rendering by caching "variable" calculation
This commit speeds up rendering partials by caching the variable name
calculation on the template.  The variable name is based on the "virtual
path" used for looking up the template.  The same virtual path
information lives on the template, so we can just ask the cached
template object for the variable.

This benchmark takes a couple files, so I'll cat them below:

```
[aaron@TC ~/g/r/actionview (speed-up-partials)]$ cat render_benchmark.rb
require "benchmark/ips"
require "action_view"
require "action_pack"
require "action_controller"

class TestController < ActionController::Base
end

TestController.view_paths = [File.expand_path("test/benchmarks")]
controller_view = TestController.new.view_context

result = Benchmark.ips do |x|
  x.report("render") do
    controller_view.render("many_partials")
  end
end
[aaron@TC ~/g/r/actionview (speed-up-partials)]$ cat test/benchmarks/test/_many_partials.html.erb
Looping:
<ul>
<% 100.times do |i| %>
  <%= render partial: "list_item", locals: { i: i } %>
<% end %>
</ul>
[aaron@TC ~/g/r/actionview (speed-up-partials)]$ cat test/benchmarks/test/_list_item.html.erb
<li>Number: <%= i %></li>
```

Benchmark results (master):

```
[aaron@TC ~/g/r/actionview (master)]$ be ruby render_benchmark.rb
Warming up --------------------------------------
              render    41.000  i/100ms
Calculating -------------------------------------
              render    424.269  (± 3.5%) i/s -      2.132k in   5.031455s
```

Benchmark results (this branch):

```
[aaron@TC ~/g/r/actionview (speed-up-partials)]$ be ruby render_benchmark.rb
Warming up --------------------------------------
              render    50.000  i/100ms
Calculating -------------------------------------
              render    521.862  (± 3.8%) i/s -      2.650k in   5.085885s
```
2019-02-05 15:24:21 -08:00
Ryuta Kamizono 0f3e8e1ebb Relation no longer respond to Arel methods
This follows up d97980a16d.
2019-02-06 04:58:45 +09:00
Ryuta Kamizono 2935d07569 Chaining named scope is no longer leaking to class level querying methods
Active Record uses `scoping` to delegate to named scopes from relations
for propagating the chaining source scope. It was needed to restore the
source scope in named scopes, but it was caused undesired behavior that
pollute all class level querying methods.

Example:

```ruby
class Topic < ActiveRecord::Base
  scope :toplevel, -> { where(parent_id: nil) }
  scope :children, -> { where.not(parent_id: nil) }
  scope :has_children, -> { where(id: Topic.children.select(:parent_id)) }
end

# Works as expected.
Topic.toplevel.where(id: Topic.children.select(:parent_id))

# Doesn't work due to leaking `toplevel` to `Topic.children`.
Topic.toplevel.has_children
```

Since #29301, the receiver in named scopes has changed from the model
class to the chaining source scope, so the polluting class level
querying methods is no longer required for that purpose.

Fixes #14003.
2019-02-06 00:37:08 +09:00
Ryuta Kamizono eec3e28a1a
Merge pull request #35127 from bogdan/counter-cache-loading
Bugfix association loading behavior when counter cache is zero
2019-02-05 20:32:37 +09:00
Bogdan Gusiev f1b64dff47 Bugfix association loading behavior when counter cache is zero 2019-02-05 11:58:59 +02:00
Aaron Patterson 3cace9eac9
Merge pull request #35154 from sponomarev/chore/sqlite1.4
Relax sqlite3 version dependency
2019-02-04 13:31:44 -08:00
Rafael Mendonça França cc2d614e63
Improve performance of blank? and present? in an ActiveRecord::Base instance
With this benchmark:

    require "bundler/setup"

    require "active_record"
    require "benchmark/ips"

    # This connection will do for database-independent bug reports.
    ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")

    ActiveRecord::Schema.define do
      create_table :posts, force: true do |t|
      end
    end

    class Post < ActiveRecord::Base
    end

    new_post = Post.new

    Benchmark.ips do |b|
      b.report("present?") do
        new_post.present?
      end

      b.report("blank?") do
        new_post.blank?
      end
    end

Before:

    Warming up --------------------------------------
                present?    52.147k i/100ms
                  blank?    53.077k i/100ms
    Calculating -------------------------------------
                present?    580.184k (±21.8%) i/s -      2.555M in   5.427085s
                  blank?    601.537k (± 9.2%) i/s -      2.972M in   5.003503s

After:

    Warming up --------------------------------------
                present?   378.235k i/100ms
                  blank?   375.476k i/100ms
    Calculating -------------------------------------
                present?     17.381M (± 7.5%) i/s -     86.238M in   5.001815s
                  blank?     17.877M (± 6.4%) i/s -     88.988M in   5.004634s

This improvement is mostly because those methods were hitting
`method_missing` on a lot of levels to be able to return the value.

To avoid all this stack walking we are short-circuiting those methods.

Closes #35059.
2019-02-04 15:56:47 -05:00
Sergey Ponomarev 2a29202288
Relax sqlite3 version dependency 2019-02-04 15:21:40 -05:00
Eileen M. Uchitelle 7d85d3847e
Merge pull request #35089 from eileencodes/fix-query-cache-for-database-switching
Invalidate all query caches for current thread
2019-02-04 08:46:10 -05:00
Eileen M. Uchitelle f4aed53e44
Merge pull request #35132 from eileencodes/allow-application-to-change-handler-names
Add ability to change the names of the default handlers
2019-02-04 08:45:48 -05:00
Gannon McGibbon 00f7dbab75
Merge pull request #35105 from olivierlacan/document-table-foreign-key
Hint at advanced options for foreign_key
2019-02-02 16:08:55 -05:00
Eileen Uchitelle 183c0eb472 Invalidate query cache for all connections in the current thread
This change ensures that all query cahces are cleared across all
connections per handler for the current thread so if you write on one
connection the read will have the query cache cleared.
2019-02-01 16:05:25 -05:00
Eileen Uchitelle 8d32346cde Add ability to change the names of the default handlers
When I wrote the `connected_to` and `connects_to` API's I wrote them
with the idea in mind that it didn't really matter what the
handlers/roles were called as long as those connecting to the roles knew
which one wrote and which one read.

With the introduction of the middleware Rails begins to assume it's
`writing` and `reading` and there's no room for other roles. At GitHub
we've been using this method for a long time so we have a ton of legacy
code that uses different handler names `default` and `readonly`. We
could rename all our code but I think this is better for a few reasons:

- Legacy apps that have been using multiple databases for a long time
  can have an eaiser time switching.
- If we later find this to cause more issues than it's worth we can
  easily deprecate.
- We won't force old apps to rewrite the resolver middleware just to use
  a different handler.

Adding the writing_role/reading_role required that I move the code that
creates the first handler for writing to the railtie. If I didn't move
this the core class would assign the handler before I was able to assign
a new one in my configuration and I'd end up with 3 handlers instead of
2.
2019-02-01 14:11:35 -05:00
Eileen M. Uchitelle caf8dbc159
Merge pull request #35130 from rails/move-delay-to-options-argument
Refactor options for database selector middleware
2019-02-01 13:53:34 -05:00
Rafael França bc0cad0690
Merge pull request #35082 from Shopify/eagerly-materialize-test-transactions
Eagerly materialize the fixtures transaction
2019-02-01 13:41:44 -05:00
Eileen Uchitelle 31f205234a Refactor options for middleware
Right now we only have one option that's supported, the delay. However I
can see us supporting other options in the future.

This PR refactors the options to get passed into the resolver so whether
you're using middleware or using the config options you can pass options
to the resolver. This will also make it easy to add new options in the
future.
2019-02-01 11:34:50 -05:00
Ryuta Kamizono 6127b8d920
Merge pull request #35116 from kamipo/fix_through_association_creation
Fix has_many through association creation
2019-02-01 09:13:43 +09:00
Ryuta Kamizono 0413501691 Remove unused attr_writers `visitor` and `indexes`
I deprecated two unused attr_writers `visitor` and `indexes` at 8056fe0
and f4bc364 conservatively, since those are accidentaly exposed in the
docs.

https://api.rubyonrails.org/v5.2/classes/ActiveRecord/ConnectionAdapters/AbstractAdapter.html
https://api.rubyonrails.org/v5.2/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html

But I've found that `view_renderer` attr_writer is removed without
deprecation at #35093, that is also exposed in the doc.

https://api.rubyonrails.org/v5.2/classes/ActionView/Base.html

I'd like to also remove the deprecated attr_writers since I think that
removing `visitor` and `indexes` attr_writers is as safe as removing
`view_renderer` attr_writer.
2019-02-01 02:32:01 +09:00
Ryuta Kamizono 42d20e8de5 Revert "Merge pull request #33729 from kddeisz/plural-automatic-inverse"
This reverts commit ed1eda271c, reversing
changes made to 3d2caab7dc.

Reason: 7c3da6e003
2019-02-01 01:34:49 +09:00
alkesh26 379354572f ActiveRecord typo fixe. 2019-01-31 16:31:51 +05:30
Abhay Nikam 15db608f3e Fixed typo for DatabaseSelector::Resolver documentation 2019-01-31 07:57:38 +05:30
Ryuta Kamizono 1f5e21bcbc Remove redundant begin block
We enabled `Style/RedundantBegin` cop at #34764, but it is hard to
detect an offence if returning value put after the block.
2019-01-31 10:18:34 +09:00
Olivier Lacan 13f8beb435 Hint at advanced options for foreign_key
We sometimes display simple examples of additional parameters that can be
supplied to table-wise methods like these and I found it particularly difficult
to figure out which options `t.foreign_key` accepts without drilling very deep
into the specific SchemaStatements docs.

Since it's relatively common to create foreign keys with custom column names or
primary keys, it seems like this should help quite a few people.

[ci skip]
2019-01-30 19:29:03 -05:00
John Hawthorn ab952b1949 Write update_last_write_timestamp after request
We need to update using the timestamp from the end of the request, not
the start. For example, if a request spends 5+ seconds writing, we still
want to wait another 5 seconds for replication lag.

Since we now run the update after we yield, we need to use ensure to
make sure we update the timestamp even if there is an exception.
2019-01-30 13:25:09 -08:00
Eileen M. Uchitelle 8ca6bd2e94
Merge pull request #35073 from eileencodes/db-selection
Part 8: Multi db improvements, Adds basic automatic database switching to Rails
2019-01-30 14:03:45 -05:00
Eileen Uchitelle 0abcec416b Adds basic automatic database switching to Rails
The following PR adds behavior to Rails to allow an application to
automatically switch it's connection from the primary to the replica.

A request will be sent to the replica if:

* The request is a read request (`GET` or `HEAD`)
* AND It's been 2 seconds since the last write to the database (because
we don't want to send a user to a replica if the write hasn't made it
to the replica yet)

A request will be sent to the primary if:

* It's not a GET/HEAD request (ie is a POST, PATCH, etc)
* Has been less than 2 seconds since the last write to the database

The implementation that decides when to switch reads (the 2 seconds) is
"safe" to use in production but not recommended without adequate testing
with your infrastructure. At GitHub in addition to the a 5 second delay
we have a curcuit breaker that checks the replication delay
and will send the query to a replica before the 5 seconds has passed.
This is specific to our application and therefore not something Rails
should be doing for you. You'll need to test and implement more robust
handling of when to switch based on your infrastructure. The auto
switcher in Rails is meant to be a basic implementation / API that acts
as a guide for how to implement autoswitching.

The impementation here is meant to be strict enough that you know how to
implement your own resolver and operations classes but flexible enough
that we're not telling you how to do it.

The middleware is not included automatically and can be installed in
your application with the classes you want to use for the resolver and
operations passed in. If you don't pass any classes into the middleware
the Rails default Resolver and Session classes will be used.

The Resolver decides what parameters define when to
switch, Operations sets timestamps for the Resolver to read from. For
example you may want to use cookies instead of a session so you'd
implement a Resolver::Cookies class and pass that into the middleware
via configuration options.

```
config.active_record.database_selector = { delay: 2.seconds }
config.active_record.database_resolver = MyResolver
config.active_record.database_operations = MyResolver::MyCookies
```

Your classes can inherit from the existing classes and reimplment the
methods (or implement more methods) that you need to do the switching.
You only need to implement methods that you want to change. For example
if you wanted to set the session token for the last read from a replica
you would reimplement the `read_from_replica` method in your resolver
class and implement a method that updates a new timestamp in your
operations class.
2019-01-30 13:37:25 -05:00
Eileen Uchitelle dedcc19506 Fix case when we want a UrlConfig but the URL is nil
Previously if the `url` key in a config hash was nil we'd ignore the
configuration as invalid. This can happen when you're relying on a
`DATABASE_URL` in the env and that is not set in the environment.

```
production:
  <<: *default
  url: ENV['DATABASE_URL']
```

This PR fixes that case by checking if there is a `url` key in the
config instead of checking if the `url` is not nil in the config.

In addition to changing the conditional we then need to build a url hash
to merge with the original hash in the `UrlConfig` object.

Fixes #35091
2019-01-30 09:31:35 -05:00
Jean Boussier 74dbce0fca Eagerly materialize the fixtures transaction
The transaction used to restore fixtures is an implementation detail
that should be abstracted away. Idealy a test should behave the same
wether or not transactional fixtures are enabled.

However since transactions have been made lazy, the fixture
transaction started leaking into tests case. e.g. consider the
following (oversimplified) test:

```ruby
class SQLSubscriber
  attr_accessor :sql

  def initialize
    @sql = []
  end

  def call(*, event)
    sql << event[:sql]
  end
end

subscriber = SQLSubscriber.new
ActiveSupport::Notifications.subscribe("sql.active_record", subscriber)

User.connection.execute('SELECT 1', 'Generic name')
assert_equal ['SELECT 1'], subscriber.sql
```

On Rails 6 it starts to break because the `sql` array will be `['BEGIN', 'SELECT 1']`.

Several things are wrong here:

  - That transaction is not generated by the tested code, so it shouldn't be visible.
  - The transaction is not even closed yet, which again doesn't reflect the reality.
2019-01-29 16:10:47 +01:00
Ryuta Kamizono 8309cd2c68
Merge pull request #35071 from kamipo/text_without_limit
MySQL: Support `:size` option to change text and blob size
2019-01-29 17:02:04 +09:00
Aaron Patterson 5bb1ad59b1
Pull `@template` in to a local variable
This gets the PartialRenderer to be a bit closer to the
TemplateRenderer.  TemplateRenderer already keeps its template in a
local variable.
2019-01-28 14:55:12 -08:00
Aaron Patterson e98b51300a
Remove `@view` instance variable from the partial renderer
Similar to 1853b0d0ab
2019-01-28 14:22:32 -08:00
Ryuta Kamizono 1745e905a3 Allow changing text and blob size without giving the `limit` option
In MySQL, the text column size is 65,535 bytes by default (1 GiB in
PostgreSQL). It is sometimes too short when people want to use a text
column, so they sometimes change the text size to mediumtext (16 MiB) or
longtext (4 GiB) by giving the `limit` option.

Unlike MySQL, PostgreSQL doesn't allow the `limit` option for a text
column (raises ERROR: type modifier is not allowed for type "text").
So `limit: 4294967295` (longtext) couldn't be used in Action Text.

I've allowed changing text and blob size without giving the `limit`
option, it prevents that migration failure on PostgreSQL.
2019-01-29 06:49:32 +09:00
Lars Kanis c6d7e70be4 PostgreSQL: Use native timestamp decoders of pg-1.1
This improves performance of timestamp conversion and avoids
additional string allocations.
2019-01-26 20:30:43 +01:00
Ryuta Kamizono 57015cdfa2 Make `t.timestamps` with precision by default 2019-01-26 22:49:14 +09:00
Ryuta Kamizono 5fe6d3747e Fix `t.timestamps` missing `null: false` in `change_table bulk: true` 2019-01-26 21:19:20 +09:00
Ryuta Kamizono 17901d8764 Allow `column_exists?` giving options without type 2019-01-26 21:14:28 +09:00
Eileen M. Uchitelle bf3a8a0e6c
Merge pull request #35042 from eileencodes/fix-error-message-for-missing-handler
Fix error raised when handler doesn't exist
2019-01-25 10:56:00 -05:00
Eileen Uchitelle 1284f826cc Fix error raised when handler doesn't exist
While working on another feature for multiple databases (auto-switching)
I observed that in development the first request won't autoload the
application record connection for the primary database and may not yet
know about the replica connection.

In my test application this caused the application to thrown an error if
I tried to send the first request to the replica before the replica was
connected. This wouldn't be an issue in production because the
application is preloaded.

In order to fix this I decided to leave the original error message and
delete the new error message. I updated the original error message to
include the `role` to make it a bit clearer that the connection isn't
established for that particular role.

The error now reads:

```
No connection pool with 'primary' found for the 'reading' role.
```

A single database application will continue uisng the original error
message:

```
No connection pool with 'primary' found.
```
2019-01-25 09:56:43 -05:00
Kevin Deisz 5cf36e2ea2
Make `And` and `Case` into expression nodes
Allows aliasing, predications, ordering, and various other functions on `And` and `Case` nodes. This brings them in line with other nodes like `Binary` and `Unary`.
2019-01-24 14:35:52 -05:00
Ryuta Kamizono 1fecebae31 Allow `column_exists?` to be passed `type` argument as a string
Currently `conn.column_exists?("testings", "created_at", "datetime")`
returns false even if the table has the `created_at` column.

That reason is that `column.type` is a symbol but passed `type` is not
normalized to symbol unlike `column_name`, it is surprising behavior to
me.

I've improved that to normalize a value before comparison.
2019-01-24 19:02:44 +09:00
Xavier Noria 0065011660 Tell the user what to use instead of update_attributes/! 2019-01-23 22:26:22 +01:00
Dylan Thacker-Smith 5b58cc4f44 activerecord: Fix statement cache for strictly cast attributes 2019-01-23 14:49:42 -05:00
Yasuo Honda 3ea3cccc93 MySQL 8.0.14 adds `ER_FK_INCOMPATIBLE_COLUMNS`
https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-14.html
> Error messages relating to creating and dropping foreign keys
> were improved to be more specific and informative. (Bug #28526309, Bug #92087)

https://dev.mysql.com/doc/refman/8.0/en/server-error-reference.html

> Error number: 3780; Symbol: ER_FK_INCOMPATIBLE_COLUMNS; SQLSTATE: HY000
> Message: Referencing column '%s' and referenced column '%s' in foreign key constraint '%s' are incompatible.
> ER_FK_INCOMPATIBLE_COLUMNS was added in 8.0.14.
2019-01-22 15:15:52 +00:00
Kevin Deisz 65cec345b4
Alias case nodes
When `Arel` was merged into `ActiveRecord` we lost the ability to alias case nodes. This adds it back.
2019-01-21 10:28:39 -05:00
Ryuta Kamizono 4a0e3809be Fix type casting column default in `change_column`
Since #31230, `change_column` is executed as a bulk statement.

That caused incorrect type casting column default by looking up the
before changed type, not the after changed type.

In a bulk statement, we can't use `change_column_default_for_alter` if
the statement changes the column type.

This fixes the type casting to use the constructed target sql_type.

Fixes #34938.
2019-01-20 11:09:00 +09:00
Rafael Mendonça França 5a0230c67f
Preparing for 6.0.0.beta1 release 2019-01-18 15:42:12 -05:00
Dylan Thacker-Smith 592a961f29 activerecord: Fix where nil condition on composed_of attribute 2019-01-18 11:10:10 -05:00
Ryuta Kamizono ff3d1a42d5
Merge pull request #30000 from kamipo/all_of_queries_should_return_correct_result
All of queries should return correct result even if including large number
2019-01-18 22:58:54 +09:00
Eileen M. Uchitelle 7235e84935
Merge pull request #34969 from eileencodes/fix-error-message-for-multi-db-apps
Fix error message when adapter is not specified
2019-01-18 07:53:26 -05:00
Ryuta Kamizono c196ca72a0 Ensure `StatementCache#execute` never raises `RangeError`
Since 31ffbf8d, finder methods no longer raise `RangeError`. So
`StatementCache#execute` is the only place to raise the exception for
finder queries.

`StatementCache` is used for simple equality queries in the codebase.
This means that if `StatementCache#execute` raises `RangeError`, the
result could always be regarded as empty.
So `StatementCache#execute` just return nil in that range error case,
and treat that as empty in the caller side, then we can avoid catching
the exception in much places.
2019-01-18 16:01:14 +09:00