Commit Graph

1536 Commits

Author SHA1 Message Date
Sean Griffin
1bdc395d95 Make the second argument to attribute optional
While working on updating Paper Trail for 5.1 compatibility, I noticed
that I was required to pass a second argument to `attribute`. I didn't
intend for this to be the case, as `attribute :foo` is totally
reasonable shorthand for "I want `attr_accessor :foo`, but also have it
work with things like `.attributes` and `ActiveRecord::Dirty`"
2016-11-30 12:47:31 -05:00
Ryuta Kamizono
32ea84df6f Fix that unsigned with zerofill is treated as signed
Fixes #27125.
2016-11-27 22:38:59 +09:00
Sergey Alekseev
8a0fda63aa fix the uniqueness validation scope with a polymorphic association
https://gist.github.com/sergey-alekseev/946657ebdb5e58d1bee115714056ec96
2016-11-26 18:49:00 +03:00
Dominic Cleal
935502062e
Add test for collection *_ids= setter when association primary key set
Fixes casting of IDs to the data type of the association primary key,
rather than then the data type of the model's primary key. (Tests use a
string primary key on the association, rather than an int.)

Tests issue #20995
2016-11-24 09:29:40 +00:00
Dominic Cleal
15e2da656f
Restore RecordNotFound when *_ids= can't find records by ID
9c9fb19 changed the behaviour of the _ids= setters for associations to
raise an AssociationTypeMismatch when unknown IDs are given:

    Class: <ActiveRecord::AssociationTypeMismatch>
    Message: <"Developer(#43811860) expected, got NilClass(#16732720)">

This restores the original ActiveRecord::RecordNotFound exception with a
much clearer error message:

    Class: <ActiveRecord::RecordNotFound>
    Message: <"Couldn't find all Developers with 'id': (1, -9999) [WHERE \"contracts\".\"company_id\" = ?] (found 1 results, but was looking for 2)">

Fixes #25719
2016-11-24 09:27:33 +00:00
Yaw Boakye
b915b11cca
For PostgreSQL >= 9.4 use gen_random_uuid()
Since 9.4, PostgreSQL recommends using `pgcrypto`'s `gen_random_uuid()`
to generate version 4 UUIDs instead of the functions in the `uuid-ossp`
extension.

These changes uses the appropriate UUID function depending on the
underlying PostgreSQL server's version, while maintaining
`uuid_generate_v4()` in older migrations.
2016-11-22 22:11:18 +00:00
Yves Senn
0e9957135d Introduce reload_<association> reader for singular associations.
This patch brings back the functionality of passing true to the
association proxy. The behavior was deprecated with #20888 and scheduled
for removal in Rails 5.1.

The deprecation mentioned that instead of `Article.category(true)` one
should use `article#reload.category`. Unfortunately the alternative does
not expose the same behavior as passing true to the reader
did. Specifically reloading the parent record throws unsaved changes and
other caches away. Passing true only affected the association.

This is problematic and there is no easy workaround. I propose to bring
back the old functionality by introducing this new reader method for
singular associations.
2016-11-22 12:37:42 +01:00
Yves Senn
e49237387b changelog entry for fc4c15d [ci skip]
fc4c15d823
2016-11-21 12:56:20 +01:00
Rafael França
c659cb8561 Merge pull request #26981 from kamipo/should_not_except_order_for_exists
Should except `:distinct` rather than `:order` for `exists?`
2016-11-17 18:27:25 -05:00
Jon Moss
0a8b212db7 Support AC::Parameters for PG HStore
As reported via #26904, there is a regression in how values for
Postgres' HStore column type are being processed, beginning in Rails 5.
Currently, the way that Active Record checks whether or not values need
to be serialized and put into the correct storage format is whether or
not it is a `Hash` object. Since `ActionController::Parameters` no
longer inherits from `Hash` in Rails 5, this conditional now returns
false. To remedy this, we are now checking to see whether the `value`
parameters being passed in responds to a certain method, and then
calling the `serialize` method, except this time with a real Hash
object. Keeping things DRY!

Fixes #26904.
2016-11-15 16:42:44 -05:00
Vipul A M
7e7d6ccf34
Changelog edits 2016-11-12 13:14:49 -05:00
Ryuta Kamizono
2bf7c30049 Should except :distinct rather than :order for exists?
Records fetching order is very important for performance if `limit` is
presented. Should not except the order in the case.

And `exists?` replaces select list to `1 AS one` therefore `:distinct`
is useless (`DISTINCT 1 AS one`). And PostgreSQL raises the following
error if `:distinct` and `:order` are used in the same time.

```
ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list
```
2016-11-09 18:47:39 +09:00
Pavel
35b6898f7c Add ActiveRecord::Base.connection_pool.stat 2016-11-09 01:10:16 +08:00
Ryuta Kamizono
62bb8b9dfd Avoid unscope(:order) when limit_value is presented for count
If `limit_value` is presented, records fetching order is very important
for performance. Should not unscope the order in the case.
2016-11-06 02:56:26 +09:00
Sen-Zhang
9bf4583241 fix datatime error 2016-11-01 18:17:26 -07:00
Cohen Carlisle
1d6b62026b allow ActiveRecord::Core#slice to use array arg 2016-10-31 11:14:45 -04:00
Arthur Neves
a0a37d9fd3
Merge PR #19759
Fix for has_and_belongs_to_many & has_many_through associations
2016-10-28 17:15:23 -04:00
Sean Griffin
331d080a66 Revert "Made ActiveRecord consistently use ActiveRecord::Type (not"
This reverts commit 671eb742eec77b5c8281ac2a2e3976ef32a6e424.

This is not a change we would like moving forward.
2016-10-23 09:19:54 +03:00
Prathamesh Sonpatki
56bfaf7f03
Fix regression caused due to removal of select method from CollectionAssociation
- CollectionAssociation#select was removed in
  https://github.com/rails/rails/pull/25989 in favor of
  QueryMethods#select but it caused a regression when passing arguments
  to select and a block.
- This used to work earlier in Rails 4.2 and Rails 5. See gist
  https://gist.github.com/prathamesh-sonpatki/a7df922273473a77dfbc742a4be4b618.
- This commit restores the behavior of Rails 4.2 and Rails 5.0.0 to
  allow passing arguments and block at the same time but also deprecates
  it.
- Because, these arguments do not have any effect on the output of
  select when select is used with a block.
- Updated documentation to remove the example passing arguments and
  block at the same time to `CollectionProxy#select`.
2016-10-22 09:04:47 +05:30
bogdanvlviv
a60a20bb7f Added ability update locking_column value 2016-10-21 19:06:02 +03:00
bogdanvlviv
22a822e581 Fixed: Optimistic locking does not work well with null in the database 2016-10-21 19:06:02 +03:00
Matthew Draper
bc9dc41825 Merge pull request #26208 from nanaya/pg-insensitive-text
Fix case insensitive check for text column in pg
2016-10-11 12:23:15 +10:30
Iain Beeston
671eb742ee Made ActiveRecord consistently use ActiveRecord::Type (not
ActiveModel::Type)

Some code was previously referring to ActiveModel::Type::*. This could
cause issues in the future if any of the ActiveRecord::Type classes were
overridden in the future.
2016-10-03 16:42:26 +01:00
Trung Duc Tran
21675fdc44 Serialize JSON attribute value nil as SQL NULL, not JSON 'null'
Test: JSON attribute value nil can be used in where(attr: nil)

Add changelog entry
2016-09-23 11:38:38 -07:00
Prathamesh Sonpatki
730e99affb
Return true if attribute is not changed for update_attribute
- If the attribute is not changed, then update_attribute does not run
  SQL query, this effectively means that no change was made to the
  attribute.
- This change was made in https://github.com/rails/rails/commit/0fcd4cf5
  to avoid a SQL call.
- But the change resulted into `nil` being returned when there was no
  change in the attribute value.
- This commit corrects the behavior to return true if there is no change
  in attribute value. This is same as previous behavior of Rails 4.2
  plus benefit of no additional SQL call.
- Fixes #26593.
2016-09-23 15:24:55 +05:30
Rafael Mendonça França
d406014b03
Always store errors details information with symbols
When the association is autosaved we were storing the details with
string keys. This was creating inconsistency with other details that are
added using the `Errors#add` method. It was also inconsistent with the
`Errors#messages` storage.

To fix this inconsistency we are always storing with symbols. This will
cause a small breaking change because in those cases the details could
be accessed as strings keys but now it can not.

The reason that we chose to do this breaking change is because `#details`
should be considered a low level object like `#messages` is.

Fix #26499.

[Rafael Mendonça França + Marcus Vieira]
2016-09-19 19:57:03 -03:00
Jakob Skjerning
e835596ae8 Clear attribute changes after handling locking
Without this the changes to the lock version column will stick around
even after `touch` returns.

Before:

    model.touch
    model.changes
    # => {"lock_version"=>[0, "1"]}

After:

    model.touch
    model.changes
    # {}
2016-09-14 17:37:04 +02:00
Dylan Thacker-Smith
88ff3f820a
5-0-backport: activerecord/mysql2: Avoid setting @connection to nil, just close it (#26473)
* activerecord/mysql2: Avoid setting @connection to nil, just close it

Backport of https://github.com/rails/rails/pull/26434

* Add a CHANGELOG entry
2016-09-13 14:19:15 -04:00
Sean Griffin
7ba3a48df5 Attempt to maintain encoding for arrays of strings with PG
I still think that this is something that should be handled in the pg
gem, but it's not going to end up happening there so we'll do it here
instead. Once we bump to pg 0.19 we can pass the encoding to the
`encode` method instead.

This issue occurs because C has no concept of encoding (or strings,
really). The bytes that we pass here when sending the value to the
database will always be interpreted as whatever encoding the connection
is currently configured to use. That means that roundtripping to the
database will lose no information

However, after assigning we round trip through our type system without
hitting the database. The only way that we can do the "correct" thin
here would be to actually give a reference to the connection to the
array type and have it check the current value of the connection's
encoding -- which I'm strongly opposed to. We could also pass in the
encoding when it's constructed, but since that can change independently
of the type I'm not a huge fan of that either.

This feels like a reasonable middle ground, where if we have an array of
strings we simply use the encoding of the string we're given.

Fixes #26326.
2016-08-31 12:06:30 -04:00
Sean Griffin
caa178c178 Ensure that inverse associations are set before running callbacks
If a parent association was accessed in an `after_find` or
`after_initialize` callback, it would always end up loading the
association, and then immediately overwriting the association we just
loaded. If this occurred in a way that the parent's `current_scope` was
set to eager load the child, this would result in an infinite loop and
eventually overflow the stack.

For records that are created with `.new`, we have a mechanism to
perform an action before the callbacks are run. I've introduced the same
code path for records created with `instantiate`, and updated all code
which sets inverse instances on newly loaded associations to use this
block instead.

Fixes #26320.
2016-08-31 09:26:25 -04:00
James Coleman
a94fe2971b Don't unnecessarily load a belongs_to when saving.
Previously, if the the association was previously loaded and then
the foreign key changed by itself, a #save call would trigger a
load of the new associated record during autosave. This is unnecessary
and the autosave code (in that case) didn't use the loaded record
anyways.
2016-08-26 11:40:38 -04:00
Rafael Mendonça França
df84e98672
Remove the SchemaDumper options and change the default behavior
Now the schema dumper by default doesn't align the types and arguments
in the ruby format anymore.
2016-08-22 15:46:04 -03:00
Rafael Mendonça França
e87158f16b
Merge pull request #25675 from TimPetricola/schema-no-standardized-column-widths
Option not to line up column attributes in schema.rb
2016-08-19 01:28:39 -03:00
Rafael Mendonça França
15175fdad7
Add chengelog entry to #25976
[Rafael Mendonça França + Robin Dupret]
2016-08-19 01:08:09 -03:00
Rafael Mendonça França
bdf24f883f
Merge pull request #26154 from kamipo/remove_text_default_treated_as_empty_string
Remove text default treated as an empty string in non-strict mode
2016-08-19 01:04:03 -03:00
Rafael Mendonça França
eabf024369
Merge pull request #26089 from travisoneill/sqlite_rollback_fix
Sqlite3 Migration Error Fixed (issue #26087)
2016-08-19 00:26:02 -03:00
Ryuta Kamizono
99cb16a2ba Remove text default treated as an empty string in non-strict mode
Strict mode controls how MySQL handles invalid or missing values in
data-change statements such as INSERT or UPDATE. If strict mode is not
in effect, MySQL inserts adjusted values for invalid or missing values
and produces warnings.

```ruby
  def test_mysql_not_null_defaults_non_strict
    using_strict(false) do
      with_mysql_not_null_table do |klass|
        record = klass.new
        assert_nil record.non_null_integer
        assert_nil record.non_null_string
        assert_nil record.non_null_text
        assert_nil record.non_null_blob

        record.save!
        record.reload

        assert_equal 0,  record.non_null_integer
        assert_equal "", record.non_null_string
        assert_equal "", record.non_null_text
        assert_equal "", record.non_null_blob
      end
    end
  end
```

It is inconsistent with other types that only text/blob defaults treated
as an empty string. This commit fixes the inconsistency.
2016-08-19 12:11:26 +09:00
travis.h.oneill@gmail.com
906ff07e71 Added nil case handling to allow rollback migration in case of
invalid column type
    /activerecord/lib/active_record/connection_adapters
    /abstract/schema_definitions.rb:306
    type = type.to_sym

Changed to the following to handle nil case:
    type = type.to_sym if type

Added regression test for this case:
  /activerecord/test/cases/migration_test.rb:554
  if current_adapter?(:SQLite3Adapter)
    def test_allows_sqlite3_rollback_on_invalid_column_type
      Person.connection.create_table :something, force: true do |t|
        t.column :number, :integer
        t.column :name, :string
        t.column :foo, :bar
      end
      assert Person.connection.column_exists?(:something, :foo)
      assert_nothing_raised { Person.connection.remove_column :something, :foo, :bar }
      assert !Person.connection.column_exists?(:something, :foo)
      assert Person.connection.column_exists?(:something, :name)
      assert Person.connection.column_exists?(:something, :number)
    ensure
      Person.connection.drop_table :something, if_exists: true
    end
  end
2016-08-17 17:21:54 -07:00
Ryuta Kamizono
6eaf5c9253 Deprecate sanitize_conditions. Use sanitize_sql instead
Because `sanitize_conditions` protected method is only used in one place.
2016-08-18 02:00:57 +09:00
Tim Petricola
dde3bdf214 Option not to line up column types and attributes in schema.rb 2016-08-17 10:09:34 +02:00
Maxime Lapointe
0aae7806c1 Fix count which would sometimes force a DISTINCT
The current behaviour of checking if there is a LEFT OUTER JOIN arel
node to detect if we are doing eager_loading is wrong. This problem
wasn't frequent before as only some pretty specific cases would add
a LEFT OUTER JOIN arel node. However, the recent new feature
left_outer_joins also add this node and made this problem happen
frequently.

Since in the perform_calculation function, we don't have access to
eager_loading information, I had to extract the logic for the distinct
out to the calculate method.

As I was in the file for left_outer_join tests, I fixed a few that had
bugs and I replaced some that were really weak with something that
will catch more issues.

In relation tests, the first test I changed would have failed if it
had validated the hash returned by count instead of just checking how
many pairs were in it. This is because this merge of join currently
transforms the join node into an outer join node, which then made
count do a distinct. So before this change, the return was
{1=>1, 4=>1, 5=>1}.
2016-08-16 09:45:23 -04:00
Michel Pigassou
cafdbeba90 When calling association.find RecordNotFound is now raised with the same argument as when we do it in Record.find (primary_key, id and model). 2016-08-13 12:41:45 -07:00
Vipul A M
8b984161d6
Pass over changelogs [ci skip] 2016-08-10 09:33:13 +05:30
Sean Griffin
b63d532f1e Don't assume all hashes are from multiparameter assignment in composed_of
So this bug is kinda funky. The code path is basically "if we weren't passed an
instance of the class we compose to, and we have a converter, call that".
Ignoring the hash case for a moment, everything after that was roughly intended
to be the "else" clause, meaning that we are expected to have an instance of
the class we compose to. Really, we should be blowing up in that case, as we
can give a much better error message than what they user will likely get (e.g.
`NameError: No method first for String` or something). Still, Ruby is duck
typed, so if the object you're assigning responds to the same methods as the
type you compose to, knock yourself out.

The hash case was added in 36e9be8 to remove a bunch of special cased code from
multiparameter assignment. I wrongly assumed that the only time we'd get a hash
there is in that case. Multiparameter assignment will construct a very specific
hash though, where the keys are integers, and we will have a set of keys
covering `1..part.size` exactly. I'm pretty sure this could actually be passed
around as an array, but that's a different story. Really I should convert this
to something like `class MultiParameterAssignment < Hash; end`, which I might
do soon. However for a change that I'm willing to backport to 4-2-stable, this
is what I want to go with for the time being.

Fixes #25978
2016-08-05 09:52:09 -04:00
Takeshi AKIMA
ea1dcbbc99 Add the TABLE_SCHEMA condition to the SELECT statement in table_comment (#25945)
[Rafael Mendonça França + Takeshi AKIMA]
2016-07-27 23:19:08 -03:00
Sean Griffin
aa7a6047c2 Whoops, forgot the changelog entry for the previous commit 2016-07-25 11:13:01 -04:00
Rafael Mendonça França
9c6f348d79
Merge pull request #25849 from suginoy/fix_merge_in_scope
Fix the calling `merge` method at first in a scope
2016-07-20 02:11:17 -03:00
alpaca-tc
780535017a Fixes multiparameter attributes conversion with time_zone_aware_attributes and invalid params 2016-07-19 22:35:45 +09:00
suginoy
cf2574b1c9 Fix the calling merge method at first in a scope
Changing the order of method chaining `merge` and other query
method such as `joins` should produce the same result.

```ruby
class Topic < ApplicationRecord
  scope :safe_chaininig,   -> { joins(:comments).merge(Comment.newest) }
  scope :unsafe_chaininig, -> { merge(Comment.newest).joins(:comments) } #=> NoMethodError
end
```
2016-07-19 10:19:59 +09:00
Prathamesh Sonpatki
91251fdcbd
CHANGELOG for https://github.com/rails/rails/pull/25257 [ci skip]
- Also minor weekly CHANGELOG cleanup.
2016-07-17 11:27:06 +05:30