Skip to content

Simplify attribute type decoration - #39882

Merged
kamipo merged 3 commits into
rails:masterfrom
kamipo:simplify_attribute_type_decoration
Jul 20, 2020
Merged

kamipo merged 3 commits into
rails:masterfrom
kamipo:simplify_attribute_type_decoration

Conversation

@kamipo

@kamipo kamipo commented Jul 19, 2020

Copy link
Copy Markdown
Member

Using decorate_matching_attribute_type is overkill to do that.

Using `decorate_matching_attribute_type` is overkill to do that.
@eugeneius

Copy link
Copy Markdown
Member

define_attribute runs three times: when the schema loads, when attributes are defined, and when attributes are decorated. That means these type decorations will now be applied at least twice, and potentially three times since user-defined attributes can also be decorations (#39820, #39830). I don't think the additional runtime overhead is worth the simplification here.

@eugeneius

Copy link
Copy Markdown
Member

We could extract a method to override during the attribute decoration phase instead:

diff --git a/activerecord/lib/active_record/attribute_decorators.rb b/activerecord/lib/active_record/attribute_decorators.rb
index 0b66043d2a..32aed3329d 100644
--- a/activerecord/lib/active_record/attribute_decorators.rb
+++ b/activerecord/lib/active_record/attribute_decorators.rb
@@ -49,10 +49,14 @@ def decorate_matching_attribute_types(matcher, decorator_name, &block)
         def load_schema!
           super
           attribute_types.each do |name, type|
-            decorated_type = attribute_type_decorations.apply(name, type)
+            decorated_type = apply_attribute_type_decorations(name, type)
             define_attribute(name, decorated_type)
           end
         end
+
+        def apply_attribute_type_decorations(name, type)
+          attribute_type_decorations.apply(name, type)
+        end
     end

     class TypeDecorator # :nodoc:
diff --git a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
index f97412b1cd..5a294305e7 100644
--- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
+++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
@@ -64,7 +64,7 @@ def map_avoiding_infinite_recursion(value)
       end

       module ClassMethods # :nodoc:
-        def define_attribute(name, cast_type, **)
+        def apply_attribute_type_decorations(name, cast_type)
           if create_time_zone_conversion_attribute?(name, cast_type)
             cast_type = TimeZoneConverter.new(cast_type)
           end
diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb
index 8770909086..80082f4575 100644
--- a/activerecord/lib/active_record/locking/optimistic.rb
+++ b/activerecord/lib/active_record/locking/optimistic.rb
@@ -165,7 +165,7 @@ def update_counters(id, counters)
             super
           end

-          def define_attribute(name, cast_type, **) # :nodoc:
+          def apply_attribute_type_decorations(name, cast_type) # :nodoc:
             if lock_optimistically && name == locking_column
               cast_type = LockingType.new(cast_type)
             end

The internal attribute decoration is almost covered by the `attribute`
with block, we don't need to have much code and extra class attribute.
@kamipo
kamipo force-pushed the simplify_attribute_type_decoration branch from 7d9d785 to d784043 Compare July 20, 2020 04:27
@kamipo

kamipo commented Jul 20, 2020

Copy link
Copy Markdown
Member Author

The purpose of the simplification is to remove much extra code, extra class attribute, and extra hook point, I've extracted the first commit as an easier review part (I supposed no one disagree the smaller part).

If you prefer the extraction, I can pick the diff first before the removing.

@kamipo

kamipo commented Jul 20, 2020

Copy link
Copy Markdown
Member Author

As the code (attribute_types.each do ...) shows, originally all registered decoration matchers are invoked for all defined attributes, so unless having user-defined attributes on the database columns, so the number of invocations of decoration matchers does not change.

def load_schema!
super
attribute_types.each do |name, type|
decorated_type = attribute_type_decorations.apply(name, type)
define_attribute(name, decorated_type)
end
end

Let me know if still have any concerns.

@eugeneius

Copy link
Copy Markdown
Member

My concern isn't how often the decoration matcher runs, but how many times the type is decorated.

diff --git a/activerecord/test/cases/attributes_test.rb b/activerecord/test/cases/attributes_test.rb
index 15475d12d8..14f2ddd4d6 100644
--- a/activerecord/test/cases/attributes_test.rb
+++ b/activerecord/test/cases/attributes_test.rb
@@ -87,6 +87,7 @@ class CustomPropertiesTest < ActiveRecord::TestCase
           attribute :starts_at, :datetime, precision: 3, default: -> { Time.now.utc }
         end

+        assert_instance_of ActiveSupport::Type::DateTime, klass.type_for_attribute(:starts_at).__getobj__
         assert_instance_of ActiveSupport::TimeWithZone, klass.new.starts_at
       end
     end
Failure:
ActiveRecord::CustomPropertiesTest#test_time_zone_aware_attribute [/Users/eugene/src/rails/activerecord/test/cases/attributes_test.rb:90]:
Expected #<ActiveRecord::Type::DateTime:0x00007ff3d8df1640 @precision=3, @scale=nil, @limit=nil> to be an instance of ActiveRecord::Type::DateTime, not ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter.

The second commit resolves ☝️, but the same problem remains for user-defined timezone attributes that don't specify a type, which was the motivating example for #39830. Do you not consider this double-typecasting at runtime to be a problem?

@eugeneius

Copy link
Copy Markdown
Member

I agree that the AttributeDecorators abstraction is too heavyweight for the small number of places it's actually used, by the way. I do think this is a good change, I'd just prefer not to regress runtime performance at all if possible.

@kamipo

kamipo commented Jul 20, 2020

Copy link
Copy Markdown
Member Author

The second commit resolves ☝️, but the same problem remains for user-defined timezone attributes that don't specify a type, which was the motivating example for #39830. Do you not consider this double-typecasting at runtime to be a problem?

I've get your point. I'll address that in a later commit.

I agree that the AttributeDecorators abstraction is too heavyweight for the small number of places it's actually used, by the way. I do think this is a good change, I'd just prefer not to regress runtime performance at all if possible.

As I said above, the purpose of the simplification is to remove much extra code, extra class attribute, and extra hook point.

About runtime performance, as long as the number of invocations of decoration matchers is the same (i.e. not having user-defined attributes on the database columns), removing the extra load_schema! hook point (it avoids extra re-define_attribute, and changes slower block matcher invocation to just a method call) obviously makes lesser overhead than before.

I am missing something about the performance?

def load_schema!
super
attribute_types.each do |name, type|
decorated_type = attribute_type_decorations.apply(name, type)
define_attribute(name, decorated_type)
end
end

@eugeneius

Copy link
Copy Markdown
Member

Yes, removing that stuff will definitely make defining attributes faster. By "runtime performance" I meant when the application is serving requests, rather than when it's initialising; I was thinking of the overhead of the double-typecasting.

@kamipo
kamipo force-pushed the simplify_attribute_type_decoration branch from 832f0d8 to f83f14b Compare July 20, 2020 10:07
…mp attribute with implicit type

If type is given as a symbol, it will lookup a fresh type object via
`Type.lookup`, but if type is omitted, `type_for_attribute` will lookup
the database type which is already decorated by `define_attribute`.

To avoid the double decoration, skip extra decoration if its type is
already decorated.
@kamipo
kamipo force-pushed the simplify_attribute_type_decoration branch from f83f14b to e036602 Compare July 20, 2020 10:56
@kamipo

kamipo commented Jul 20, 2020

Copy link
Copy Markdown
Member Author

I've addressed the double decoration e036602, it no longer have runtime overhead.

jonathanhefner added a commit to jonathanhefner/rails that referenced this pull request Jul 20, 2020
This is an alternate take on rails#39882, based on top of rails#38871.

Co-authored-by: Ryuta Kamizono <[email protected]>
Comment on lines +76 to +78
if type && !type.is_a?(Proc)
cast_type = _lookup_cast_type(attr_name, type, options)
end

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like this type.is_a?(Proc) check is here to avoid decorating with Type::Serialized twice, but there are now multiple ways that the type could be specified as a proc. How about checking the type directly:

Suggested change
if type && !type.is_a?(Proc)
cast_type = _lookup_cast_type(attr_name, type, options)
end
cast_type = _lookup_cast_type(attr_name, type, options) if type
cast_type = cast_type.subtype if cast_type.is_a?(Type::Serialized)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Originally there is no official way to decorate with Type::Serialized twice.

Personally I'd like to remove this part entirely, but existing tests expects serialize can overlay on the user-defined attribute. This part is for passing the tests.

attribute :payload, :json
attribute :settings, :json

new_klass = Class.new(klass) do
serialize :settings, MySettings
end

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personally I'd like to remove this part entirely, but existing tests expects serialize can overlay on the user-defined attribute. This part is for passing the tests.

In other words, we need to allow serialize on user-defined attribute with symbol for passing tests, but I'd not like to allow serialize on user-defined attribute with block which is internally used feature.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, my suggestion is another way to make those tests pass. I find cast_type.is_a?(Type::Serialized) easier to understand than type.is_a?(Proc).

But it's just a preference, there's no practical benefit. I think I've delayed this PR enough. Thanks for your patience 🙇

@kamipo
kamipo merged commit b949e69 into rails:master Jul 20, 2020
@kamipo
kamipo deleted the simplify_attribute_type_decoration branch July 20, 2020 23:47
jonathanhefner added a commit to jonathanhefner/rails that referenced this pull request Jul 26, 2020
`AttributeDecorators` was removed in rails#39882 in favor of calling the
`attribute` macro with a block.  However, this technique overwrote the
original attribute type, which is still needed by some decorators.  Thus
those decorators had to bypass the encapsulation of the `Attributes`
module to retrieve the original attribute type.

This commit makes the `attribute` macro retain the original attribute
type when a new type is not specified.
kamipo added a commit that referenced this pull request Jul 27, 2020
Originally #39882 is intended to remove `decorate_matching_attribute_type`
but leave `decorate_attribute_type` at that point, but in the
disscussion in #39882, to demonstrate removing `AttributeDecorators`
module, I've removed all decoration methods.

I wrote user-defined type decoration as inline, I wasn't sure that is
valid (meaningful) usage (that is a reason why I wasn't in a hurry to
remove that method), as I said at #39882 (comment).

In #39897 and #39902, `enum` also need to support user-defined type
decoration, so I've decided to add back `decorate_attribute_type` as
before #39882.
y-yagi added a commit to y-yagi/enumerize that referenced this pull request Nov 10, 2020
y-yagi added a commit to y-yagi/enumerize that referenced this pull request Nov 20, 2020
y-yagi added a commit to y-yagi/enumerize that referenced this pull request Nov 28, 2020
y-yagi added a commit to y-yagi/enumerize that referenced this pull request Nov 29, 2020
y-yagi added a commit to y-yagi/enumerize that referenced this pull request Nov 29, 2020
alpaca-tc pushed a commit to alpaca-tc/enumerize that referenced this pull request Dec 6, 2020
alpaca-tc pushed a commit to alpaca-tc/enumerize that referenced this pull request Dec 6, 2020
mygreatstory pushed a commit to mygreatstory/rubenumerize that referenced this pull request Jan 9, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants