Hello community,

here is the log from the commit of package rubygem-activerecord-5_1 for 
openSUSE:Factory checked in at 2018-02-18 11:44:26
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Comparing /work/SRC/openSUSE:Factory/rubygem-activerecord-5_1 (Old)
 and      /work/SRC/openSUSE:Factory/.rubygem-activerecord-5_1.new (New)
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Package is "rubygem-activerecord-5_1"

Sun Feb 18 11:44:26 2018 rev:4 rq:577554 version:5.1.5

Changes:
--------
--- 
/work/SRC/openSUSE:Factory/rubygem-activerecord-5_1/rubygem-activerecord-5_1.changes
        2017-11-20 17:07:29.721224352 +0100
+++ 
/work/SRC/openSUSE:Factory/.rubygem-activerecord-5_1.new/rubygem-activerecord-5_1.changes
   2018-02-18 11:44:40.508623560 +0100
@@ -1,0 +2,156 @@
+Thu Feb 15 05:29:44 UTC 2018 - [email protected]
+
+- updated to version 5.1.5
+ see installed CHANGELOG.md
+
+  ## Rails 5.1.5 (February 14, 2018) ##
+  
+  *   Fix `count(:all)` with eager loading and having an order other than the 
driving table.
+  
+      Fixes #31783.
+  
+      *Ryuta Kamizono*
+  
+  *   Use `count(:all)` in `HasManyAssociation#count_records` to prevent 
invalid
+      SQL queries for association counting.
+  
+      *Klas Eskilson*
+  
+  *   Fix to invoke callbacks when using `update_attribute`.
+  
+      *Mike Busch*
+  
+  *   Fix `count(:all)` to correctly work `distinct` with custom SELECT list.
+  
+      *Ryuta Kamizono*
+  
+  *   Fix conflicts `counter_cache` with `touch: true` by optimistic locking.
+  
+      ```
+      # create_table :posts do |t|
+      #   t.integer :comments_count, default: 0
+      #   t.integer :lock_version
+      #   t.timestamps
+      # end
+      class Post < ApplicationRecord
+      end
+  
+      # create_table :comments do |t|
+      #   t.belongs_to :post
+      # end
+      class Comment < ApplicationRecord
+        belongs_to :post, touch: true, counter_cache: true
+      end
+      ```
+  
+      Before:
+      ```
+      post = Post.create!
+      # => begin transaction
+           INSERT INTO "posts" ("created_at", "updated_at", "lock_version")
+           VALUES ("2017-12-11 21:27:11.387397", "2017-12-11 21:27:11.387397", 
0)
+           commit transaction
+  
+      comment = Comment.create!(post: post)
+      # => begin transaction
+           INSERT INTO "comments" ("post_id") VALUES (1)
+  
+           UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) 
+ 1,
+           "lock_version" = COALESCE("lock_version", 0) + 1 WHERE "posts"."id" 
= 1
+  
+           UPDATE "posts" SET "updated_at" = '2017-12-11 21:27:11.398330',
+           "lock_version" = 1 WHERE "posts"."id" = 1 AND 
"posts"."lock_version" = 0
+           rollback transaction
+      # => ActiveRecord::StaleObjectError: Attempted to touch a stale object: 
Post.
+  
+      Comment.take.destroy!
+      # => begin transaction
+           DELETE FROM "comments" WHERE "comments"."id" = 1
+  
+           UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) 
- 1,
+           "lock_version" = COALESCE("lock_version", 0) + 1 WHERE "posts"."id" 
= 1
+  
+           UPDATE "posts" SET "updated_at" = '2017-12-11 21:42:47.785901',
+           "lock_version" = 1 WHERE "posts"."id" = 1 AND 
"posts"."lock_version" = 0
+           rollback transaction
+      # => ActiveRecord::StaleObjectError: Attempted to touch a stale object: 
Post.
+      ```
+  
+      After:
+      ```
+      post = Post.create!
+      # => begin transaction
+           INSERT INTO "posts" ("created_at", "updated_at", "lock_version")
+           VALUES ("2017-12-11 21:27:11.387397", "2017-12-11 21:27:11.387397", 
0)
+           commit transaction
+  
+      comment = Comment.create!(post: post)
+      # => begin transaction
+           INSERT INTO "comments" ("post_id") VALUES (1)
+  
+           UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) 
+ 1,
+           "lock_version" = COALESCE("lock_version", 0) + 1,
+           "updated_at" = '2017-12-11 21:37:09.802642' WHERE "posts"."id" = 1
+           commit transaction
+  
+      comment.destroy!
+      # => begin transaction
+           DELETE FROM "comments" WHERE "comments"."id" = 1
+  
+           UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) 
- 1,
+           "lock_version" = COALESCE("lock_version", 0) + 1,
+           "updated_at" = '2017-12-11 21:39:02.685520' WHERE "posts"."id" = 1
+           commit transaction
+      ```
+  
+      Fixes #31199.
+  
+      *bogdanvlviv*
+  
+  *   Query cache was unavailable when entering the `ActiveRecord::Base.cache` 
block
+      without being connected.
+  
+      *Tsukasa Oishi*
+  
+  *   Fix `bin/rails db:setup` and `bin/rails db:test:prepare` create  wrong
+      ar_internal_metadata's data for a test database.
+  
+      Before:
+      ```
+      $ RAILS_ENV=test rails dbconsole
+      > SELECT * FROM ar_internal_metadata;
+      key|value|created_at|updated_at
+      environment|development|2017-09-11 23:14:10.815679|2017-09-11 
23:14:10.815679
+      ```
+  
+      After:
+      ```
+      $ RAILS_ENV=test rails dbconsole
+      > SELECT * FROM ar_internal_metadata;
+      key|value|created_at|updated_at
+      environment|test|2017-09-11 23:14:10.815679|2017-09-11 23:14:10.815679
+      ```
+  
+      Fixes #26731.
+  
+      *bogdanvlviv*
+  
+  *   Fix longer sequence name detection for serial columns.
+  
+      Fixes #28332.
+  
+      *Ryuta Kamizono*
+  
+  *   MySQL: Don't lose `auto_increment: true` in the `db/schema.rb`.
+  
+      Fixes #30894.
+  
+      *Ryuta Kamizono*
+  
+  *   Fix `COUNT(DISTINCT ...)` for `GROUP BY` with `ORDER BY` and `LIMIT`.
+  
+      Fixes #30886.
+  
+      *Ryuta Kamizono*
+
+-------------------------------------------------------------------

Old:
----
  activerecord-5.1.4.gem

New:
----
  activerecord-5.1.5.gem

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Other differences:
------------------
++++++ rubygem-activerecord-5_1.spec ++++++
--- /var/tmp/diff_new_pack.SugFia/_old  2018-02-18 11:44:42.560549899 +0100
+++ /var/tmp/diff_new_pack.SugFia/_new  2018-02-18 11:44:42.560549899 +0100
@@ -1,7 +1,7 @@
 #
 # spec file for package rubygem-activerecord-5_1
 #
-# Copyright (c) 2017 SUSE LINUX GmbH, Nuernberg, Germany.
+# Copyright (c) 2018 SUSE LINUX GmbH, Nuernberg, Germany.
 #
 # All modifications and additions to the file contributed by third parties
 # remain the property of their copyright owners, unless otherwise agreed
@@ -24,7 +24,7 @@
 #
 
 Name:           rubygem-activerecord-5_1
-Version:        5.1.4
+Version:        5.1.5
 Release:        0
 %define mod_name activerecord
 %define mod_full_name %{mod_name}-%{version}

++++++ activerecord-5.1.4.gem -> activerecord-5.1.5.gem ++++++
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/CHANGELOG.md new/CHANGELOG.md
--- old/CHANGELOG.md    2017-09-08 02:48:53.000000000 +0200
+++ new/CHANGELOG.md    2018-02-14 20:54:31.000000000 +0100
@@ -1,3 +1,154 @@
+## Rails 5.1.5 (February 14, 2018) ##
+
+*   Fix `count(:all)` with eager loading and having an order other than the 
driving table.
+
+    Fixes #31783.
+
+    *Ryuta Kamizono*
+
+*   Use `count(:all)` in `HasManyAssociation#count_records` to prevent invalid
+    SQL queries for association counting.
+
+    *Klas Eskilson*
+
+*   Fix to invoke callbacks when using `update_attribute`.
+
+    *Mike Busch*
+
+*   Fix `count(:all)` to correctly work `distinct` with custom SELECT list.
+
+    *Ryuta Kamizono*
+
+*   Fix conflicts `counter_cache` with `touch: true` by optimistic locking.
+
+    ```
+    # create_table :posts do |t|
+    #   t.integer :comments_count, default: 0
+    #   t.integer :lock_version
+    #   t.timestamps
+    # end
+    class Post < ApplicationRecord
+    end
+
+    # create_table :comments do |t|
+    #   t.belongs_to :post
+    # end
+    class Comment < ApplicationRecord
+      belongs_to :post, touch: true, counter_cache: true
+    end
+    ```
+
+    Before:
+    ```
+    post = Post.create!
+    # => begin transaction
+         INSERT INTO "posts" ("created_at", "updated_at", "lock_version")
+         VALUES ("2017-12-11 21:27:11.387397", "2017-12-11 21:27:11.387397", 0)
+         commit transaction
+
+    comment = Comment.create!(post: post)
+    # => begin transaction
+         INSERT INTO "comments" ("post_id") VALUES (1)
+
+         UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) + 
1,
+         "lock_version" = COALESCE("lock_version", 0) + 1 WHERE "posts"."id" = 
1
+
+         UPDATE "posts" SET "updated_at" = '2017-12-11 21:27:11.398330',
+         "lock_version" = 1 WHERE "posts"."id" = 1 AND "posts"."lock_version" 
= 0
+         rollback transaction
+    # => ActiveRecord::StaleObjectError: Attempted to touch a stale object: 
Post.
+
+    Comment.take.destroy!
+    # => begin transaction
+         DELETE FROM "comments" WHERE "comments"."id" = 1
+
+         UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) - 
1,
+         "lock_version" = COALESCE("lock_version", 0) + 1 WHERE "posts"."id" = 
1
+
+         UPDATE "posts" SET "updated_at" = '2017-12-11 21:42:47.785901',
+         "lock_version" = 1 WHERE "posts"."id" = 1 AND "posts"."lock_version" 
= 0
+         rollback transaction
+    # => ActiveRecord::StaleObjectError: Attempted to touch a stale object: 
Post.
+    ```
+
+    After:
+    ```
+    post = Post.create!
+    # => begin transaction
+         INSERT INTO "posts" ("created_at", "updated_at", "lock_version")
+         VALUES ("2017-12-11 21:27:11.387397", "2017-12-11 21:27:11.387397", 0)
+         commit transaction
+
+    comment = Comment.create!(post: post)
+    # => begin transaction
+         INSERT INTO "comments" ("post_id") VALUES (1)
+
+         UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) + 
1,
+         "lock_version" = COALESCE("lock_version", 0) + 1,
+         "updated_at" = '2017-12-11 21:37:09.802642' WHERE "posts"."id" = 1
+         commit transaction
+
+    comment.destroy!
+    # => begin transaction
+         DELETE FROM "comments" WHERE "comments"."id" = 1
+
+         UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) - 
1,
+         "lock_version" = COALESCE("lock_version", 0) + 1,
+         "updated_at" = '2017-12-11 21:39:02.685520' WHERE "posts"."id" = 1
+         commit transaction
+    ```
+
+    Fixes #31199.
+
+    *bogdanvlviv*
+
+*   Query cache was unavailable when entering the `ActiveRecord::Base.cache` 
block
+    without being connected.
+
+    *Tsukasa Oishi*
+
+*   Fix `bin/rails db:setup` and `bin/rails db:test:prepare` create  wrong
+    ar_internal_metadata's data for a test database.
+
+    Before:
+    ```
+    $ RAILS_ENV=test rails dbconsole
+    > SELECT * FROM ar_internal_metadata;
+    key|value|created_at|updated_at
+    environment|development|2017-09-11 23:14:10.815679|2017-09-11 
23:14:10.815679
+    ```
+
+    After:
+    ```
+    $ RAILS_ENV=test rails dbconsole
+    > SELECT * FROM ar_internal_metadata;
+    key|value|created_at|updated_at
+    environment|test|2017-09-11 23:14:10.815679|2017-09-11 23:14:10.815679
+    ```
+
+    Fixes #26731.
+
+    *bogdanvlviv*
+
+*   Fix longer sequence name detection for serial columns.
+
+    Fixes #28332.
+
+    *Ryuta Kamizono*
+
+*   MySQL: Don't lose `auto_increment: true` in the `db/schema.rb`.
+
+    Fixes #30894.
+
+    *Ryuta Kamizono*
+
+*   Fix `COUNT(DISTINCT ...)` for `GROUP BY` with `ORDER BY` and `LIMIT`.
+
+    Fixes #30886.
+
+    *Ryuta Kamizono*
+
+
 ## Rails 5.1.4 (September 07, 2017) ##
 
 *   No changes.
Binary files old/checksums.yaml.gz and new/checksums.yaml.gz differ
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' 
old/lib/active_record/associations/belongs_to_association.rb 
new/lib/active_record/associations/belongs_to_association.rb
--- old/lib/active_record/associations/belongs_to_association.rb        
2017-09-08 02:48:53.000000000 +0200
+++ new/lib/active_record/associations/belongs_to_association.rb        
2018-02-14 20:54:31.000000000 +0100
@@ -47,9 +47,9 @@
         def update_counters(by)
           if require_counter_update? && foreign_key_present?
             if target && !stale_target?
-              target.increment!(reflection.counter_cache_column, by)
+              target.increment!(reflection.counter_cache_column, by, touch: 
reflection.options[:touch])
             else
-              klass.update_counters(target_id, reflection.counter_cache_column 
=> by)
+              klass.update_counters(target_id, reflection.counter_cache_column 
=> by, touch: reflection.options[:touch])
             end
           end
         end
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/associations/builder/belongs_to.rb 
new/lib/active_record/associations/builder/belongs_to.rb
--- old/lib/active_record/associations/builder/belongs_to.rb    2017-09-08 
02:48:53.000000000 +0200
+++ new/lib/active_record/associations/builder/belongs_to.rb    2018-02-14 
20:54:31.000000000 +0100
@@ -114,9 +114,13 @@
         BelongsTo.touch_record(record, record.send(changes_method), 
foreign_key, n, touch, belongs_to_touch_method)
       }}
 
-      model.after_save    callback.(:saved_changes), if: :saved_changes?
-      model.after_touch   callback.(:changes_to_save)
-      model.after_destroy callback.(:changes_to_save)
+      unless reflection.counter_cache_column
+        model.after_create callback.(:saved_changes), if: :saved_changes?
+        model.after_destroy callback.(:changes_to_save)
+      end
+
+      model.after_update callback.(:saved_changes), if: :saved_changes?
+      model.after_touch callback.(:changes_to_save)
     end
 
     def self.add_default_callbacks(model, reflection)
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' 
old/lib/active_record/associations/has_many_association.rb 
new/lib/active_record/associations/has_many_association.rb
--- old/lib/active_record/associations/has_many_association.rb  2017-09-08 
02:48:53.000000000 +0200
+++ new/lib/active_record/associations/has_many_association.rb  2018-02-14 
20:54:31.000000000 +0100
@@ -61,7 +61,7 @@
           count = if reflection.has_cached_counter?
             owner._read_attribute(reflection.counter_cache_column).to_i
           else
-            scope.count
+            scope.count(:all)
           end
 
           # If there's nothing in the database and @target has no new records
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' 
old/lib/active_record/associations/join_dependency/join_association.rb 
new/lib/active_record/associations/join_dependency/join_association.rb
--- old/lib/active_record/associations/join_dependency/join_association.rb      
2017-09-08 02:48:53.000000000 +0200
+++ new/lib/active_record/associations/join_dependency/join_association.rb      
2018-02-14 20:54:31.000000000 +0100
@@ -40,15 +40,7 @@
 
             constraint = build_constraint(klass, table, key, foreign_table, 
foreign_key)
 
-            predicate_builder = PredicateBuilder.new(TableMetadata.new(klass, 
table))
-            scope_chain_items = reflection.join_scopes(table, 
predicate_builder)
-            klass_scope       = reflection.klass_join_scope(table, 
predicate_builder)
-
-            scope_chain_items.concat [klass_scope].compact
-
-            rel = scope_chain_items.inject(scope_chain_items.shift) do |left, 
right|
-              left.merge right
-            end
+            rel = reflection.join_scope(table)
 
             if rel && !rel.arel.constraints.empty?
               binds += rel.bound_attributes
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/associations/join_dependency.rb 
new/lib/active_record/associations/join_dependency.rb
--- old/lib/active_record/associations/join_dependency.rb       2017-09-08 
02:48:53.000000000 +0200
+++ new/lib/active_record/associations/join_dependency.rb       2018-02-14 
20:54:31.000000000 +0100
@@ -126,7 +126,7 @@
       end
 
       def aliases
-        Aliases.new join_root.each_with_index.map { |join_part, i|
+        @aliases ||= Aliases.new join_root.each_with_index.map { |join_part, i|
           columns = join_part.column_names.each_with_index.map { |column_name, 
j|
             Aliases::Column.new column_name, "t#{i}_r#{j}"
           }
@@ -134,7 +134,7 @@
         }
       end
 
-      def instantiate(result_set, aliases)
+      def instantiate(result_set, &block)
         primary_key = aliases.column_alias(join_root, join_root.primary_key)
 
         seen = Hash.new { |i, object_id|
@@ -157,7 +157,7 @@
         message_bus.instrument("instantiation.active_record", payload) do
           result_set.each { |row_hash|
             parent_key = primary_key ? row_hash[primary_key] : row_hash
-            parent = parents[parent_key] ||= join_root.instantiate(row_hash, 
column_aliases)
+            parent = parents[parent_key] ||= join_root.instantiate(row_hash, 
column_aliases, &block)
             construct(parent, join_root, row_hash, result_set, seen, 
model_cache, aliases)
           }
         end
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' 
old/lib/active_record/associations/preloader/association.rb 
new/lib/active_record/associations/preloader/association.rb
--- old/lib/active_record/associations/preloader/association.rb 2017-09-08 
02:48:53.000000000 +0200
+++ new/lib/active_record/associations/preloader/association.rb 2018-02-14 
20:54:31.000000000 +0100
@@ -90,7 +90,11 @@
           end
 
           def key_conversion_required?
-            @key_conversion_required ||= association_key_type != owner_key_type
+            unless defined?(@key_conversion_required)
+              @key_conversion_required = (association_key_type != 
owner_key_type)
+            end
+
+            @key_conversion_required
           end
 
           def convert_key(key)
@@ -127,42 +131,15 @@
           end
 
           def build_scope
-            scope = klass.unscoped
-
-            values = reflection_scope.values
-            preload_values = preload_scope.values
-
-            scope.where_clause = reflection_scope.where_clause + 
preload_scope.where_clause
-            scope.references_values = Array(values[:references]) + 
Array(preload_values[:references])
-
-            if preload_values[:select] || values[:select]
-              scope._select!(preload_values[:select] || values[:select])
-            end
-            scope.includes! preload_values[:includes] || values[:includes]
-            if preload_scope.joins_values.any?
-              scope.joins!(preload_scope.joins_values)
-            else
-              scope.joins!(reflection_scope.joins_values)
-            end
-
-            if order_values = preload_values[:order] || values[:order]
-              scope.order!(order_values)
-            end
-
-            if preload_values[:reordering] || values[:reordering]
-              scope.reordering_value = true
-            end
-
-            if preload_values[:readonly] || values[:readonly]
-              scope.readonly!
-            end
+            scope = klass.scope_for_association
 
-            if options[:as]
-              scope.where!(klass.table_name => { reflection.type => 
model.base_class.sti_name })
+            if reflection.type
+              scope.where!(reflection.type => model.base_class.sti_name)
             end
 
-            scope.unscope_values = Array(values[:unscope]) + 
Array(preload_values[:unscope])
-            klass.scope_for_association.merge(scope)
+            scope.merge!(reflection_scope)
+            scope.merge!(preload_scope) if preload_scope != NULL_RELATION
+            scope
           end
       end
     end
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' 
old/lib/active_record/associations/preloader/through_association.rb 
new/lib/active_record/associations/preloader/through_association.rb
--- old/lib/active_record/associations/preloader/through_association.rb 
2017-09-08 02:48:53.000000000 +0200
+++ new/lib/active_record/associations/preloader/through_association.rb 
2018-02-14 20:54:31.000000000 +0100
@@ -81,17 +81,24 @@
 
           def through_scope
             scope = through_reflection.klass.unscoped
+            values = reflection_scope.values
 
             if options[:source_type]
               scope.where! reflection.foreign_type => options[:source_type]
             else
               unless reflection_scope.where_clause.empty?
-                scope.includes_values = 
Array(reflection_scope.values[:includes] || options[:source])
+                scope.includes_values = Array(values[:includes] || 
options[:source])
                 scope.where_clause = reflection_scope.where_clause
+                if joins = values[:joins]
+                  scope.joins!(source_reflection.name => joins)
+                end
+                if left_outer_joins = values[:left_outer_joins]
+                  scope.left_outer_joins!(source_reflection.name => 
left_outer_joins)
+                end
               end
 
-              scope.references! reflection_scope.values[:references]
-              if scope.eager_loading? && order_values = 
reflection_scope.values[:order]
+              scope.references! values[:references]
+              if scope.eager_loading? && order_values = values[:order]
                 scope = scope.order(order_values)
               end
             end
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/attribute_methods/dirty.rb 
new/lib/active_record/attribute_methods/dirty.rb
--- old/lib/active_record/attribute_methods/dirty.rb    2017-09-08 
02:48:53.000000000 +0200
+++ new/lib/active_record/attribute_methods/dirty.rb    2018-02-14 
20:54:31.000000000 +0100
@@ -63,7 +63,7 @@
       end
 
       def changes_internally_applied # :nodoc:
-        @mutations_before_last_save = mutation_tracker
+        @mutations_before_last_save = mutations_from_database
         forget_attribute_assignments
         @mutations_from_database = AttributeMutationTracker.new(@attributes)
       end
@@ -71,7 +71,8 @@
       def changes_applied # :nodoc:
         @previous_mutation_tracker = mutation_tracker
         @changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
-        clear_mutation_trackers
+        @mutation_tracker = nil
+        @mutations_from_database = nil
       end
 
       def clear_changes_information # :nodoc:
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/collection_cache_key.rb 
new/lib/active_record/collection_cache_key.rb
--- old/lib/active_record/collection_cache_key.rb       2017-09-08 
02:48:53.000000000 +0200
+++ new/lib/active_record/collection_cache_key.rb       2018-02-14 
20:54:31.000000000 +0100
@@ -4,8 +4,8 @@
       query_signature = Digest::MD5.hexdigest(collection.to_sql)
       key = "#{collection.model_name.cache_key}/query-#{query_signature}"
 
-      if collection.loaded?
-        size = collection.size
+      if collection.loaded? || collection.distinct_value
+        size = collection.records.size
         if size > 0
           timestamp = 
collection.max_by(&timestamp_column)._read_attribute(timestamp_column)
         end
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' 
old/lib/active_record/connection_adapters/abstract/query_cache.rb 
new/lib/active_record/connection_adapters/abstract/query_cache.rb
--- old/lib/active_record/connection_adapters/abstract/query_cache.rb   
2017-09-08 02:48:53.000000000 +0200
+++ new/lib/active_record/connection_adapters/abstract/query_cache.rb   
2018-02-14 20:54:31.000000000 +0100
@@ -108,6 +108,7 @@
                   "sql.active_record",
                   sql: sql,
                   binds: binds,
+                  type_casted_binds: -> { type_casted_binds(binds) },
                   name: name,
                   connection_id: object_id,
                   cached: true,
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' 
old/lib/active_record/connection_adapters/abstract/schema_creation.rb 
new/lib/active_record/connection_adapters/abstract/schema_creation.rb
--- old/lib/active_record/connection_adapters/abstract/schema_creation.rb       
2017-09-08 02:48:53.000000000 +0200
+++ new/lib/active_record/connection_adapters/abstract/schema_creation.rb       
2018-02-14 20:54:31.000000000 +0100
@@ -60,7 +60,7 @@
           end
 
           def visit_PrimaryKeyDefinition(o)
-            "PRIMARY KEY (#{o.name.join(', ')})"
+            "PRIMARY KEY (#{o.name.map { |name| quote_column_name(name) 
}.join(', ')})"
           end
 
           def visit_ForeignKeyDefinition(o)
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' 
old/lib/active_record/connection_adapters/abstract/schema_definitions.rb 
new/lib/active_record/connection_adapters/abstract/schema_definitions.rb
--- old/lib/active_record/connection_adapters/abstract/schema_definitions.rb    
2017-09-08 02:48:53.000000000 +0200
+++ new/lib/active_record/connection_adapters/abstract/schema_definitions.rb    
2018-02-14 20:54:31.000000000 +0100
@@ -121,7 +121,7 @@
         end
 
         def polymorphic_options
-          as_options(polymorphic).merge(null: options[:null])
+          as_options(polymorphic).merge(options.slice(:null, :first, :after))
         end
 
         def index_options
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' 
old/lib/active_record/connection_adapters/abstract_adapter.rb 
new/lib/active_record/connection_adapters/abstract_adapter.rb
--- old/lib/active_record/connection_adapters/abstract_adapter.rb       
2017-09-08 02:48:53.000000000 +0200
+++ new/lib/active_record/connection_adapters/abstract_adapter.rb       
2018-02-14 20:54:31.000000000 +0100
@@ -4,6 +4,7 @@
 require "active_record/connection_adapters/sql_type_metadata"
 require "active_record/connection_adapters/abstract/schema_dumper"
 require "active_record/connection_adapters/abstract/schema_creation"
+require "active_support/concurrency/load_interlock_aware_monitor"
 require "arel/collectors/bind"
 require "arel/collectors/sql_string"
 
@@ -105,7 +106,7 @@
         @schema_cache        = SchemaCache.new self
         @quoted_column_names, @quoted_table_names = {}, {}
         @visitor = arel_visitor
-        @lock = Monitor.new
+        @lock = ActiveSupport::Concurrency::LoadInterlockAwareMonitor.new
 
         if 
self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { 
true })
           @prepared_statements = true
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' 
old/lib/active_record/connection_adapters/abstract_mysql_adapter.rb 
new/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
--- old/lib/active_record/connection_adapters/abstract_mysql_adapter.rb 
2017-09-08 02:48:53.000000000 +0200
+++ new/lib/active_record/connection_adapters/abstract_mysql_adapter.rb 
2018-02-14 20:54:31.000000000 +0100
@@ -140,11 +140,11 @@
       end
 
       def get_advisory_lock(lock_name, timeout = 0) # :nodoc:
-        query_value("SELECT GET_LOCK(#{quote(lock_name)}, #{timeout})") == 1
+        query_value("SELECT GET_LOCK(#{quote(lock_name.to_s)}, #{timeout})") 
== 1
       end
 
       def release_advisory_lock(lock_name) # :nodoc:
-        query_value("SELECT RELEASE_LOCK(#{quote(lock_name)})") == 1
+        query_value("SELECT RELEASE_LOCK(#{quote(lock_name.to_s)})") == 1
       end
 
       def native_database_types
@@ -464,12 +464,13 @@
                  fk.constraint_name AS 'name',
                  rc.update_rule AS 'on_update',
                  rc.delete_rule AS 'on_delete'
-          FROM information_schema.key_column_usage fk
-          JOIN information_schema.referential_constraints rc
+          FROM information_schema.referential_constraints rc
+          JOIN information_schema.key_column_usage fk
           USING (constraint_schema, constraint_name)
           WHERE fk.referenced_column_name IS NOT NULL
             AND fk.table_schema = #{scope[:schema]}
             AND fk.table_name = #{scope[:name]}
+            AND rc.constraint_schema = #{scope[:schema]}
             AND rc.table_name = #{scope[:name]}
         SQL
 
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/connection_adapters/column.rb 
new/lib/active_record/connection_adapters/column.rb
--- old/lib/active_record/connection_adapters/column.rb 2017-09-08 
02:48:53.000000000 +0200
+++ new/lib/active_record/connection_adapters/column.rb 2018-02-14 
20:54:31.000000000 +0100
@@ -13,7 +13,7 @@
       # +default+ is the type-casted default value, such as +new+ in 
<tt>sales_stage varchar(20) default 'new'</tt>.
       # +sql_type_metadata+ is various information about the type of the column
       # +null+ determines if this column allows +NULL+ values.
-      def initialize(name, default, sql_type_metadata = nil, null = true, 
table_name = nil, default_function = nil, collation = nil, comment: nil)
+      def initialize(name, default, sql_type_metadata = nil, null = true, 
table_name = nil, default_function = nil, collation = nil, comment: nil, **)
         @name = name.freeze
         @table_name = table_name
         @sql_type_metadata = sql_type_metadata
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' 
old/lib/active_record/connection_adapters/mysql/schema_dumper.rb 
new/lib/active_record/connection_adapters/mysql/schema_dumper.rb
--- old/lib/active_record/connection_adapters/mysql/schema_dumper.rb    
2017-09-08 02:48:53.000000000 +0200
+++ new/lib/active_record/connection_adapters/mysql/schema_dumper.rb    
2018-02-14 20:54:31.000000000 +0100
@@ -5,6 +5,7 @@
         def prepare_column_options(column)
           spec = super
           spec[:unsigned] = "true" if column.unsigned?
+          spec[:auto_increment] = "true" if column.auto_increment?
 
           if supports_virtual_columns? && column.virtual?
             spec[:as] = extract_expression_for_virtual_column(column)
@@ -15,6 +16,12 @@
           spec
         end
 
+        def column_spec_for_primary_key(column)
+          spec = super
+          spec.delete(:auto_increment) if column.type == :integer && 
column.auto_increment?
+          spec
+        end
+
         def migration_keys
           super + [:unsigned]
         end
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' 
old/lib/active_record/connection_adapters/postgresql/column.rb 
new/lib/active_record/connection_adapters/postgresql/column.rb
--- old/lib/active_record/connection_adapters/postgresql/column.rb      
2017-09-08 02:48:53.000000000 +0200
+++ new/lib/active_record/connection_adapters/postgresql/column.rb      
2018-02-14 20:54:31.000000000 +0100
@@ -5,11 +5,38 @@
       delegate :array, :oid, :fmod, to: :sql_type_metadata
       alias :array? :array
 
+      def initialize(*, max_identifier_length: 63, **)
+        super
+        @max_identifier_length = max_identifier_length
+      end
+
       def serial?
         return unless default_function
 
-        %r{\Anextval\('"?#{table_name}_#{name}_seq"?'::regclass\)\z} === 
default_function
+        if 
%r{\Anextval\('"?(?<sequence_name>.+_(?<suffix>seq\d*))"?'::regclass\)\z} =~ 
default_function
+          sequence_name_from_parts(table_name, name, suffix) == sequence_name
+        end
       end
+
+      protected
+        attr_reader :max_identifier_length
+
+      private
+        def sequence_name_from_parts(table_name, column_name, suffix)
+          over_length = [table_name, column_name, suffix].map(&:length).sum + 
2 - max_identifier_length
+
+          if over_length > 0
+            column_name_length = [(max_identifier_length - suffix.length - 2) 
/ 2, column_name.length].min
+            over_length -= column_name.length - column_name_length
+            column_name = column_name[0, column_name_length - [over_length, 
0].min]
+          end
+
+          if over_length > 0
+            table_name = table_name[0, table_name.length - over_length]
+          end
+
+          "#{table_name}_#{column_name}_#{suffix}"
+        end
     end
   end
 end
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' 
old/lib/active_record/connection_adapters/postgresql/quoting.rb 
new/lib/active_record/connection_adapters/postgresql/quoting.rb
--- old/lib/active_record/connection_adapters/postgresql/quoting.rb     
2017-09-08 02:48:53.000000000 +0200
+++ new/lib/active_record/connection_adapters/postgresql/quoting.rb     
2018-02-14 20:54:31.000000000 +0100
@@ -62,7 +62,7 @@
         def quote_default_expression(value, column) # :nodoc:
           if value.is_a?(Proc)
             value.call
-          elsif column.type == :uuid && /\(\)/.match?(value)
+          elsif column.type == :uuid && value.is_a?(String) && 
/\(\)/.match?(value)
             value # Does not quote function default values for UUID columns
           elsif column.respond_to?(:array?)
             value = type_cast_from_column(column, value)
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' 
old/lib/active_record/connection_adapters/postgresql/schema_statements.rb 
new/lib/active_record/connection_adapters/postgresql/schema_statements.rb
--- old/lib/active_record/connection_adapters/postgresql/schema_statements.rb   
2017-09-08 02:48:53.000000000 +0200
+++ new/lib/active_record/connection_adapters/postgresql/schema_statements.rb   
2018-02-14 20:54:31.000000000 +0100
@@ -159,7 +159,8 @@
             table_name,
             default_function,
             collation,
-            comment: comment.presence
+            comment: comment.presence,
+            max_identifier_length: max_identifier_length
           )
         end
 
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' 
old/lib/active_record/connection_adapters/postgresql_adapter.rb 
new/lib/active_record/connection_adapters/postgresql_adapter.rb
--- old/lib/active_record/connection_adapters/postgresql_adapter.rb     
2017-09-08 02:48:53.000000000 +0200
+++ new/lib/active_record/connection_adapters/postgresql_adapter.rb     
2018-02-14 20:54:32.000000000 +0100
@@ -1,5 +1,5 @@
 # Make sure we're using pg high enough for type casts and Ruby 2.2+ 
compatibility
-gem "pg", "~> 0.18"
+gem "pg", ">= 0.18", "< 2.0"
 require "pg"
 
 require "active_record/connection_adapters/abstract_adapter"
@@ -198,6 +198,7 @@
 
           def dealloc(key)
             @connection.query "DEALLOCATE #{key}" if connection_active?
+          rescue PG::Error
           end
 
           def connection_active?
@@ -364,10 +365,11 @@
       end
 
       # Returns the configured supported identifier length supported by 
PostgreSQL
-      def table_alias_length
+      def max_identifier_length
         @max_identifier_length ||= query_value("SHOW max_identifier_length", 
"SCHEMA").to_i
       end
-      alias index_name_length table_alias_length
+      alias table_alias_length max_identifier_length
+      alias index_name_length max_identifier_length
 
       # Set the authorized user for this session
       def session_auth=(user)
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' 
old/lib/active_record/connection_adapters/sqlite3_adapter.rb 
new/lib/active_record/connection_adapters/sqlite3_adapter.rb
--- old/lib/active_record/connection_adapters/sqlite3_adapter.rb        
2017-09-08 02:48:53.000000000 +0200
+++ new/lib/active_record/connection_adapters/sqlite3_adapter.rb        
2018-02-14 20:54:32.000000000 +0100
@@ -340,7 +340,7 @@
       end
 
       def add_column(table_name, column_name, type, options = {}) #:nodoc:
-        if valid_alter_table_type?(type)
+        if valid_alter_table_type?(type) && !options[:primary_key]
           super(table_name, column_name, type, options)
         else
           alter_table(table_name) do |definition|
@@ -440,18 +440,21 @@
           options[:id] = false
           create_table(to, options) do |definition|
             @definition = definition
-            @definition.primary_key(from_primary_key) if 
from_primary_key.present?
+            if from_primary_key.is_a?(Array)
+              @definition.primary_keys from_primary_key
+            end
             columns(from).each do |column|
               column_name = options[:rename] ?
                 (options[:rename][column.name] ||
                  options[:rename][column.name.to_sym] ||
                  column.name) : column.name
-              next if column_name == from_primary_key
 
               @definition.column(column_name, column.type,
                 limit: column.limit, default: column.default,
                 precision: column.precision, scale: column.scale,
-                null: column.null, collation: column.collation)
+                null: column.null, collation: column.collation,
+                primary_key: column_name == from_primary_key
+              )
             end
             yield @definition if block_given?
           end
@@ -464,6 +467,9 @@
         def copy_table_indexes(from, to, rename = {})
           indexes(from).each do |index|
             name = index.name
+            # indexes sqlite creates for internal use start with `sqlite_` and
+            # don't need to be copied
+            next if name.starts_with?("sqlite_")
             if to == "a#{from}"
               name = "t#{name}"
             elsif from == "a#{to}"
@@ -479,6 +485,7 @@
               # index name can't be the same
               opts = { name: name.gsub(/(^|_)(#{from})_/, "\\1#{to}_"), 
internal: true }
               opts[:unique] = true if index.unique
+              opts[:where] = index.where if index.where
               add_index(to, columns, opts)
             end
           end
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/gem_version.rb 
new/lib/active_record/gem_version.rb
--- old/lib/active_record/gem_version.rb        2017-09-08 02:48:53.000000000 
+0200
+++ new/lib/active_record/gem_version.rb        2018-02-14 20:54:32.000000000 
+0100
@@ -7,7 +7,7 @@
   module VERSION
     MAJOR = 5
     MINOR = 1
-    TINY  = 4
+    TINY  = 5
     PRE   = nil
 
     STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/locking/pessimistic.rb 
new/lib/active_record/locking/pessimistic.rb
--- old/lib/active_record/locking/pessimistic.rb        2017-09-08 
02:48:53.000000000 +0200
+++ new/lib/active_record/locking/pessimistic.rb        2018-02-14 
20:54:32.000000000 +0100
@@ -60,7 +60,7 @@
       # the locked record.
       def lock!(lock = true)
         if persisted?
-          if changed?
+          if has_changes_to_save?
             ActiveSupport::Deprecation.warn(<<-MSG.squish)
               Locking a record with unpersisted changes is deprecated and will 
raise an
               exception in Rails 5.2. Use `save` to persist the changes, or 
`reload` to
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/log_subscriber.rb 
new/lib/active_record/log_subscriber.rb
--- old/lib/active_record/log_subscriber.rb     2017-09-08 02:48:53.000000000 
+0200
+++ new/lib/active_record/log_subscriber.rb     2018-02-14 20:54:32.000000000 
+0100
@@ -29,7 +29,7 @@
       binds = nil
 
       unless (payload[:binds] || []).empty?
-        casted_params = type_casted_binds(payload[:binds], 
payload[:type_casted_binds])
+        casted_params = type_casted_binds(payload[:type_casted_binds])
         binds = "  " + payload[:binds].zip(casted_params).map { |attr, value|
           render_bind(attr, value)
         }.inspect
@@ -42,9 +42,8 @@
     end
 
     private
-
-      def type_casted_binds(binds, casted_binds)
-        casted_binds || ActiveRecord::Base.connection.type_casted_binds(binds)
+      def type_casted_binds(casted_binds)
+        casted_binds.respond_to?(:call) ? casted_binds.call : casted_binds
       end
 
       def render_bind(attr, value)
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/migration/compatibility.rb 
new/lib/active_record/migration/compatibility.rb
--- old/lib/active_record/migration/compatibility.rb    2017-09-08 
02:48:53.000000000 +0200
+++ new/lib/active_record/migration/compatibility.rb    2018-02-14 
20:54:32.000000000 +0100
@@ -42,11 +42,8 @@
           end
 
           if block_given?
-            super(table_name, options) do |t|
-              class << t
-                prepend TableDefinition
-              end
-              yield t
+            super do |t|
+              yield compatible_table_definition(t)
             end
           else
             super
@@ -55,11 +52,20 @@
 
         def change_table(table_name, options = {})
           if block_given?
-            super(table_name, options) do |t|
-              class << t
-                prepend TableDefinition
-              end
-              yield t
+            super do |t|
+              yield compatible_table_definition(t)
+            end
+          else
+            super
+          end
+        end
+
+        def create_join_table(table_1, table_2, column_options: {}, **options)
+          column_options.reverse_merge!(type: :integer)
+
+          if block_given?
+            super do |t|
+              yield compatible_table_definition(t)
             end
           else
             super
@@ -70,6 +76,14 @@
           super(table_name, ref_name, type: :integer, **options)
         end
         alias :add_belongs_to :add_reference
+
+        private
+          def compatible_table_definition(t)
+            class << t
+              prepend TableDefinition
+            end
+            t
+          end
       end
 
       class V4_2 < V5_0
@@ -88,11 +102,8 @@
 
         def create_table(table_name, options = {})
           if block_given?
-            super(table_name, options) do |t|
-              class << t
-                prepend TableDefinition
-              end
-              yield t
+            super do |t|
+              yield compatible_table_definition(t)
             end
           else
             super
@@ -101,11 +112,8 @@
 
         def change_table(table_name, options = {})
           if block_given?
-            super(table_name, options) do |t|
-              class << t
-                prepend TableDefinition
-              end
-              yield t
+            super do |t|
+              yield compatible_table_definition(t)
             end
           else
             super
@@ -141,6 +149,12 @@
         end
 
         private
+          def compatible_table_definition(t)
+            class << t
+              prepend TableDefinition
+            end
+            super
+          end
 
           def index_name_for_remove(table_name, options = {})
             index_name = index_name(table_name, options)
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/model_schema.rb 
new/lib/active_record/model_schema.rb
--- old/lib/active_record/model_schema.rb       2017-09-08 02:48:53.000000000 
+0200
+++ new/lib/active_record/model_schema.rb       2018-02-14 20:54:32.000000000 
+0100
@@ -85,19 +85,6 @@
     # Sets the name of the internal metadata table.
 
     ##
-    # :singleton-method: protected_environments
-    # :call-seq: protected_environments
-    #
-    # The array of names of environments where destructive actions should be 
prohibited. By default,
-    # the value is <tt>["production"]</tt>.
-
-    ##
-    # :singleton-method: protected_environments=
-    # :call-seq: protected_environments=(environments)
-    #
-    # Sets an array of names of environments where destructive actions should 
be prohibited.
-
-    ##
     # :singleton-method: pluralize_table_names
     # :call-seq: pluralize_table_names
     #
@@ -113,20 +100,6 @@
     # If true, the default table name for a Product class will be "products". 
If false, it would just be "product".
     # See table_name for the full rules on table/class naming. This is true, 
by default.
 
-    ##
-    # :singleton-method: ignored_columns
-    # :call-seq: ignored_columns
-    #
-    # The list of columns names the model should ignore. Ignored columns won't 
have attribute
-    # accessors defined, and won't be referenced in SQL queries.
-
-    ##
-    # :singleton-method: ignored_columns=
-    # :call-seq: ignored_columns=(columns)
-    #
-    # Sets the columns names the model should ignore. Ignored columns won't 
have attribute
-    # accessors defined, and won't be referenced in SQL queries.
-
     included do
       mattr_accessor :primary_key_prefix_type, instance_writer: false
 
@@ -142,16 +115,12 @@
       class_attribute :internal_metadata_table_name, instance_accessor: false
       self.internal_metadata_table_name = "ar_internal_metadata"
 
-      class_attribute :protected_environments, instance_accessor: false
-      self.protected_environments = ["production"]
-
       class_attribute :pluralize_table_names, instance_writer: false
       self.pluralize_table_names = true
 
-      class_attribute :ignored_columns, instance_accessor: false
-      self.ignored_columns = [].freeze
-
+      self.protected_environments = ["production"]
       self.inheritance_column = "type"
+      self.ignored_columns = [].freeze
 
       delegate :type_for_attribute, to: :class
 
@@ -263,6 +232,21 @@
         (parents.detect { |p| p.respond_to?(:table_name_suffix) } || 
self).table_name_suffix
       end
 
+      # The array of names of environments where destructive actions should be 
prohibited. By default,
+      # the value is <tt>["production"]</tt>.
+      def protected_environments
+        if defined?(@protected_environments)
+          @protected_environments
+        else
+          superclass.protected_environments
+        end
+      end
+
+      # Sets an array of names of environments where destructive actions 
should be prohibited.
+      def protected_environments=(environments)
+        @protected_environments = environments.map(&:to_s)
+      end
+
       # Defines the name of the table column which will store the class name 
on single-table
       # inheritance situations.
       #
@@ -282,6 +266,22 @@
         @explicit_inheritance_column = true
       end
 
+      # The list of columns names the model should ignore. Ignored columns 
won't have attribute
+      # accessors defined, and won't be referenced in SQL queries.
+      def ignored_columns
+        if defined?(@ignored_columns)
+          @ignored_columns
+        else
+          superclass.ignored_columns
+        end
+      end
+
+      # Sets the columns names the model should ignore. Ignored columns won't 
have attribute
+      # accessors defined, and won't be referenced in SQL queries.
+      def ignored_columns=(columns)
+        @ignored_columns = columns.map(&:to_s)
+      end
+
       def sequence_name
         if base_class == self
           @sequence_name ||= reset_sequence_name
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/persistence.rb 
new/lib/active_record/persistence.rb
--- old/lib/active_record/persistence.rb        2017-09-08 02:48:53.000000000 
+0200
+++ new/lib/active_record/persistence.rb        2018-02-14 20:54:32.000000000 
+0100
@@ -267,11 +267,7 @@
       verify_readonly_attribute(name)
       public_send("#{name}=", value)
 
-      if has_changes_to_save?
-        save(validate: false)
-      else
-        true
-      end
+      save(validate: false)
     end
 
     # Updates the attributes of the model from the passed-in hash and saves the
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/query_cache.rb 
new/lib/active_record/query_cache.rb
--- old/lib/active_record/query_cache.rb        2017-09-08 02:48:53.000000000 
+0200
+++ new/lib/active_record/query_cache.rb        2018-02-14 20:54:32.000000000 
+0100
@@ -5,20 +5,20 @@
       # Enable the query cache within the block if Active Record is configured.
       # If it's not, it will execute the given block.
       def cache(&block)
-        if connected?
-          connection.cache(&block)
-        else
+        if configurations.empty?
           yield
+        else
+          connection.cache(&block)
         end
       end
 
       # Disable the query cache within the block if Active Record is 
configured.
       # If it's not, it will execute the given block.
       def uncached(&block)
-        if connected?
-          connection.uncached(&block)
-        else
+        if configurations.empty?
           yield
+        else
+          connection.uncached(&block)
         end
       end
     end
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/railties/databases.rake 
new/lib/active_record/railties/databases.rake
--- old/lib/active_record/railties/databases.rake       2017-09-08 
02:48:53.000000000 +0200
+++ new/lib/active_record/railties/databases.rake       2018-02-14 
20:54:32.000000000 +0100
@@ -311,7 +311,7 @@
       begin
         should_reconnect = 
ActiveRecord::Base.connection_pool.active_connection?
         ActiveRecord::Schema.verbose = false
-        ActiveRecord::Tasks::DatabaseTasks.load_schema 
ActiveRecord::Base.configurations["test"], :ruby, ENV["SCHEMA"]
+        ActiveRecord::Tasks::DatabaseTasks.load_schema 
ActiveRecord::Base.configurations["test"], :ruby, ENV["SCHEMA"], "test"
       ensure
         if should_reconnect
           
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations[ActiveRecord::Tasks::DatabaseTasks.env])
@@ -321,7 +321,7 @@
 
     # desc "Recreate the test database from an existent structure.sql file"
     task load_structure: %w(db:test:purge) do
-      ActiveRecord::Tasks::DatabaseTasks.load_schema 
ActiveRecord::Base.configurations["test"], :sql, ENV["SCHEMA"]
+      ActiveRecord::Tasks::DatabaseTasks.load_schema 
ActiveRecord::Base.configurations["test"], :sql, ENV["SCHEMA"], "test"
     end
 
     # desc "Empty the test database"
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/reflection.rb 
new/lib/active_record/reflection.rb
--- old/lib/active_record/reflection.rb 2017-09-08 02:48:53.000000000 +0200
+++ new/lib/active_record/reflection.rb 2018-02-14 20:54:32.000000000 +0100
@@ -35,7 +35,8 @@
 
     def self.add_reflection(ar, name, reflection)
       ar.clear_reflections_cache
-      ar._reflections = ar._reflections.merge(name.to_s => reflection)
+      name = name.to_s
+      ar._reflections = ar._reflections.except(name).merge!(name => reflection)
     end
 
     def self.add_aggregate_reflection(ar, name, reflection)
@@ -187,17 +188,24 @@
       end
       deprecate :scope_chain
 
+      def join_scope(table)
+        predicate_builder = predicate_builder(table)
+        scope_chain_items = join_scopes(table, predicate_builder)
+        klass_scope       = klass_join_scope(table, predicate_builder)
+
+        scope_chain_items.inject(klass_scope || scope_chain_items.shift, 
&:merge!)
+      end
+
       def join_scopes(table, predicate_builder) # :nodoc:
         if scope
-          [ActiveRecord::Relation.create(klass, table, predicate_builder)
-            .instance_exec(&scope)]
+          [build_scope(table, predicate_builder).instance_exec(&scope)]
         else
           []
         end
       end
 
       def klass_join_scope(table, predicate_builder) # :nodoc:
-        relation = ActiveRecord::Relation.create(klass, table, 
predicate_builder)
+        relation = build_scope(table, predicate_builder)
         klass.scope_for_association(relation)
       end
 
@@ -279,7 +287,14 @@
         JoinKeys.new(join_pk(association_klass), join_fk)
       end
 
+      def build_scope(table, predicate_builder = predicate_builder(table))
+        Relation.create(klass, table, predicate_builder)
+      end
+
       private
+        def predicate_builder(table)
+          PredicateBuilder.new(TableMetadata.new(klass, table))
+        end
 
         def join_pk(_)
           foreign_key
@@ -398,7 +413,6 @@
 
       def initialize(name, scope, options, active_record)
         super
-        @automatic_inverse_of = nil
         @type         = options[:as] && (options[:foreign_type] || 
"#{options[:as]}_type")
         @foreign_type = options[:foreign_type] || "#{name}_type"
         @constructable = calculate_constructable(macro, options)
@@ -591,12 +605,14 @@
         # If it cannot find a suitable inverse association name, it returns
         # +nil+.
         def inverse_name
-          options.fetch(:inverse_of) do
-            @automatic_inverse_of ||= automatic_inverse_of
+          unless defined?(@inverse_name)
+            @inverse_name = options.fetch(:inverse_of) { automatic_inverse_of }
           end
+
+          @inverse_name
         end
 
-        # returns either false or the inverse association name that it finds.
+        # returns either +nil+ or the inverse association name that it finds.
         def automatic_inverse_of
           if can_find_inverse_of_automatically?(self)
             inverse_name = ActiveSupport::Inflector.underscore(options[:as] || 
active_record.name.demodulize).to_sym
@@ -613,8 +629,6 @@
               return inverse_name
             end
           end
-
-          false
         end
 
         # Checks if the inverse reflection that is returned from the
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/relation/calculations.rb 
new/lib/active_record/relation/calculations.rb
--- old/lib/active_record/relation/calculations.rb      2017-09-08 
02:48:53.000000000 +0200
+++ new/lib/active_record/relation/calculations.rb      2018-02-14 
20:54:32.000000000 +0100
@@ -111,7 +111,14 @@
     def calculate(operation, column_name)
       if has_include?(column_name)
         relation = construct_relation_for_association_calculations
-        relation.distinct! if operation.to_s.downcase == "count"
+
+        if operation.to_s.downcase == "count" && !distinct_value
+          relation.distinct!
+          # PostgreSQL: ORDER BY expressions must appear in SELECT list when 
using DISTINCT
+          if (column_name == :all || column_name.nil?) && select_values.empty?
+            relation.order_values = []
+          end
+        end
 
         relation.calculate(operation, column_name)
       else
@@ -195,7 +202,7 @@
         if operation == "count"
           column_name ||= select_for_count
           if column_name == :all
-            if distinct && !(has_limit_or_offset? && order_values.any?)
+            if distinct && (group_values.any? || select_values.empty? && 
order_values.empty?)
               column_name = primary_key
             end
           elsif column_name =~ /\s*DISTINCT[\s(]+/i
@@ -227,7 +234,7 @@
       def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
         column_alias = column_name
 
-        if operation == "count" && has_limit_or_offset?
+        if operation == "count" && (column_name == :all && distinct || 
has_limit_or_offset?)
           # Shortcut when limit is zero.
           return 0 if limit_value == 0
 
@@ -369,14 +376,12 @@
       end
 
       def build_count_subquery(relation, column_name, distinct)
-        relation.select_values = [
-          if column_name == :all
-            distinct ? table[Arel.star] : Arel.sql("1")
-          else
-            column_alias = Arel.sql("count_column")
-            aggregate_column(column_name).as(column_alias)
-          end
-        ]
+        if column_name == :all
+          relation.select_values = [ Arel.sql(FinderMethods::ONE_AS_ONE) ] 
unless distinct
+        else
+          column_alias = Arel.sql("count_column")
+          relation.select_values = [ 
aggregate_column(column_name).as(column_alias) ]
+        end
 
         subquery = relation.arel.as(Arel.sql("subquery_for_count"))
         select_value = operation_over_aggregate_column(column_alias || 
Arel.star, "count", false)
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/relation/finder_methods.rb 
new/lib/active_record/relation/finder_methods.rb
--- old/lib/active_record/relation/finder_methods.rb    2017-09-08 
02:48:53.000000000 +0200
+++ new/lib/active_record/relation/finder_methods.rb    2018-02-14 
20:54:32.000000000 +0100
@@ -371,17 +371,7 @@
         relation = select aliases.columns
         relation = apply_join_dependency(relation, join_dependency)
 
-        if block_given?
-          yield relation
-        else
-          if ActiveRecord::NullRelation === relation
-            []
-          else
-            arel = relation.arel
-            rows = connection.select_all(arel, "SQL", 
relation.bound_attributes)
-            join_dependency.instantiate(rows, aliases)
-          end
-        end
+        yield relation, join_dependency
       end
 
       def construct_relation_for_exists(relation, conditions)
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/relation/query_methods.rb 
new/lib/active_record/relation/query_methods.rb
--- old/lib/active_record/relation/query_methods.rb     2017-09-08 
02:48:53.000000000 +0200
+++ new/lib/active_record/relation/query_methods.rb     2018-02-14 
20:54:32.000000000 +0100
@@ -1041,6 +1041,8 @@
       def build_select(arel)
         if select_values.any?
           arel.project(*arel_columns(select_values.uniq))
+        elsif klass.ignored_columns.any?
+          arel.project(*klass.column_names.map { |field| arel_attribute(field) 
})
         else
           arel.project(@klass.arel_table[Arel.star])
         end
@@ -1177,21 +1179,24 @@
       end
       alias having_clause_factory where_clause_factory
 
+      DEFAULT_VALUES = {
+        create_with: FROZEN_EMPTY_HASH,
+        readonly: false,
+        where: Relation::WhereClause.empty,
+        having: Relation::WhereClause.empty,
+        from: Relation::FromClause.empty
+      }
+
+      Relation::MULTI_VALUE_METHODS.each do |value|
+        DEFAULT_VALUES[value] ||= FROZEN_EMPTY_ARRAY
+      end
+
+      Relation::SINGLE_VALUE_METHODS.each do |value|
+        DEFAULT_VALUES[value] = nil if DEFAULT_VALUES[value].nil?
+      end
+
       def default_value_for(name)
-        case name
-        when :create_with
-          FROZEN_EMPTY_HASH
-        when :readonly
-          false
-        when :where, :having
-          Relation::WhereClause.empty
-        when :from
-          Relation::FromClause.empty
-        when *Relation::MULTI_VALUE_METHODS
-          FROZEN_EMPTY_ARRAY
-        when *Relation::SINGLE_VALUE_METHODS
-          nil
-        else
+        DEFAULT_VALUES.fetch(name) do
           raise ArgumentError, "unknown relation value #{name.inspect}"
         end
       end
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/relation.rb 
new/lib/active_record/relation.rb
--- old/lib/active_record/relation.rb   2017-09-08 02:48:53.000000000 +0200
+++ new/lib/active_record/relation.rb   2018-02-14 20:54:32.000000000 +0100
@@ -571,7 +571,7 @@
                     relation = self
 
                     if eager_loading?
-                      find_with_associations { |rel| relation = rel }
+                      find_with_associations { |rel, _| relation = rel }
                     end
 
                     conn = klass.connection
@@ -664,7 +664,19 @@
       end
 
       def exec_queries(&block)
-        @records = eager_loading? ? find_with_associations.freeze : 
@klass.find_by_sql(arel, bound_attributes, &block).freeze
+        @records =
+          if eager_loading?
+            find_with_associations do |relation, join_dependency|
+              if ActiveRecord::NullRelation === relation
+                []
+              else
+                rows = connection.select_all(relation.arel, "SQL", 
relation.bound_attributes)
+                join_dependency.instantiate(rows, &block)
+              end.freeze
+            end
+          else
+            klass.find_by_sql(arel, bound_attributes, &block).freeze
+          end
 
         preload = preload_values
         preload += includes_values unless eager_loading?
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/lib/active_record/tasks/database_tasks.rb 
new/lib/active_record/tasks/database_tasks.rb
--- old/lib/active_record/tasks/database_tasks.rb       2017-09-08 
02:48:53.000000000 +0200
+++ new/lib/active_record/tasks/database_tasks.rb       2018-02-14 
20:54:32.000000000 +0100
@@ -223,22 +223,22 @@
         
class_for_adapter(configuration["adapter"]).new(*arguments).structure_load(filename,
 structure_load_flags)
       end
 
-      def load_schema(configuration, format = 
ActiveRecord::Base.schema_format, file = nil) # :nodoc:
+      def load_schema(configuration, format = 
ActiveRecord::Base.schema_format, file = nil, environment = env) # :nodoc:
         file ||= schema_file(format)
 
+        check_schema_file(file)
+        ActiveRecord::Base.establish_connection(configuration)
+
         case format
         when :ruby
-          check_schema_file(file)
-          ActiveRecord::Base.establish_connection(configuration)
           load(file)
         when :sql
-          check_schema_file(file)
           structure_load(configuration, file)
         else
           raise ArgumentError, "unknown format #{format.inspect}"
         end
         ActiveRecord::InternalMetadata.create_table
-        ActiveRecord::InternalMetadata[:environment] = 
ActiveRecord::Migrator.current_environment
+        ActiveRecord::InternalMetadata[:environment] = environment
       end
 
       def schema_file(format = ActiveRecord::Base.schema_format)
@@ -251,8 +251,8 @@
       end
 
       def load_schema_current(format = ActiveRecord::Base.schema_format, file 
= nil, environment = env)
-        each_current_configuration(environment) { |configuration|
-          load_schema configuration, format, file
+        each_current_configuration(environment) { |configuration, 
configuration_environment|
+          load_schema configuration, format, file, configuration_environment
         }
         ActiveRecord::Base.establish_connection(environment.to_sym)
       end
@@ -299,9 +299,10 @@
           environments = [environment]
           environments << "test" if environment == "development"
 
-          configurations = 
ActiveRecord::Base.configurations.values_at(*environments)
-          configurations.compact.each do |configuration|
-            yield configuration unless configuration["database"].blank?
+          ActiveRecord::Base.configurations.slice(*environments).each do 
|configuration_environment, configuration|
+            next unless configuration["database"]
+
+            yield configuration, configuration_environment
           end
         end
 
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/metadata new/metadata
--- old/metadata        2017-09-08 02:48:53.000000000 +0200
+++ new/metadata        2018-02-14 20:54:31.000000000 +0100
@@ -1,14 +1,14 @@
 --- !ruby/object:Gem::Specification
 name: activerecord
 version: !ruby/object:Gem::Version
-  version: 5.1.4
+  version: 5.1.5
 platform: ruby
 authors:
 - David Heinemeier Hansson
 autorequire: 
 bindir: bin
 cert_chain: []
-date: 2017-09-08 00:00:00.000000000 Z
+date: 2018-02-14 00:00:00.000000000 Z
 dependencies:
 - !ruby/object:Gem::Dependency
   name: activesupport
@@ -16,28 +16,28 @@
     requirements:
     - - '='
       - !ruby/object:Gem::Version
-        version: 5.1.4
+        version: 5.1.5
   type: :runtime
   prerelease: false
   version_requirements: !ruby/object:Gem::Requirement
     requirements:
     - - '='
       - !ruby/object:Gem::Version
-        version: 5.1.4
+        version: 5.1.5
 - !ruby/object:Gem::Dependency
   name: activemodel
   requirement: !ruby/object:Gem::Requirement
     requirements:
     - - '='
       - !ruby/object:Gem::Version
-        version: 5.1.4
+        version: 5.1.5
   type: :runtime
   prerelease: false
   version_requirements: !ruby/object:Gem::Requirement
     requirements:
     - - '='
       - !ruby/object:Gem::Version
-        version: 5.1.4
+        version: 5.1.5
 - !ruby/object:Gem::Dependency
   name: arel
   requirement: !ruby/object:Gem::Requirement
@@ -319,7 +319,9 @@
 homepage: http://rubyonrails.org
 licenses:
 - MIT
-metadata: {}
+metadata:
+  source_code_uri: https://github.com/rails/rails/tree/v5.1.5/activerecord
+  changelog_uri: 
https://github.com/rails/rails/blob/v5.1.5/activerecord/CHANGELOG.md
 post_install_message: 
 rdoc_options:
 - "--main"
@@ -338,7 +340,7 @@
       version: '0'
 requirements: []
 rubyforge_project: 
-rubygems_version: 2.6.13
+rubygems_version: 2.7.3
 signing_key: 
 specification_version: 4
 summary: Object-relational mapper framework (part of Rails).


Reply via email to