Skip to content

Added touch option to ActiveRecord::CounterCache methods. - #26995

Closed
jtrost wants to merge 2 commits into
rails:masterfrom
jtrost:counter-cache-updated-at
Closed

jtrost wants to merge 2 commits into
rails:masterfrom
jtrost:counter-cache-updated-at

Conversation

@jtrost

@jtrost jtrost commented Nov 8, 2016

Copy link
Copy Markdown
Contributor

After messing something up with the original PR I decided to close that one and start anew.

Summary

This fixes #26724. There are cases in which calling the methods in ActiveRecord::CounterCache should update the updated_at value of the affected records. For example, if a counter cache is included in a view that is fragment cached, it would be convenient if the fragment cache was expired when the counter cache was updated by changing the updated_at value.

@kaspth suggested this public API, which is implemented in this pull request:

# Uses `timestamp_attributes_for_update_in_model`:
Message.reset_counters [ 2, 18 ], comments_count: 5, touch: true

# Touch just one timestamp:
Message.reset_counters [ 2, 18 ], comments_count: 5, touch: :last_discussed_at

# The assumed rare case where you want to touch `updated_at` plus `last_discussed_at`:
Message.reset_counters [ 2, 18 ], comments_count: 5, touch: %i( updated_at last_discussed_at )

Working with the API was a bit difficult here because each method in this module has a slightly different signature. This pull request ensures compatibility with the current implementation of these methods while providing this new option. I'll go through each method to explain the changes:

.reset_counters accepts any number of counters as a splat argument, so the {touch: true} option is added as a double splat argument to separate it from the counters argument.

.update_counters accepts any number of counters as a hash. There is no way to add another argument at the end of this method signature since the current implementation looks like this:

Topic.update_counters(@topic.id, replies_count: 2, unique_replies_count: 2)

Therefore, I tacked touch: true onto the end of the counters argument, and it's removed from the hash before iterating through the counters.

.increment_counter and .decrement_counter accept a separate options hash much like .reset_counters does. These methods call .update_counters, so the options hash is merged into the counters hash.

cc @eileencodes

@rails-bot

Copy link
Copy Markdown

Thanks for the pull request, and welcome! The Rails team is excited to review your changes, and you should hear from @rafaelfranca (or someone else) soon.

If any changes to this PR are deemed necessary, please add them as extra commits. This ensures that the reviewer can see what has changed since they last reviewed the code. Due to the way GitHub handles out-of-date commits, this should also make it reasonably obvious what issues have or haven't been addressed. Large or tricky changes may require several passes of review and changes.

This repository is being automatically checked for code quality issues using Code Climate. You can see results for this analysis in the PR status below. Newly introduced issues should be fixed before a Pull Request is considered ready to review.

Please see the contribution instructions for more information.

@kaspth kaspth left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Alright, here's a massive review for you 💪

I really like where this is going 😁

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

def reset_counters(id, *counters, touch: nil, **options) should work, no?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Still mentions updated_at: true.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

def update_counters(id, touch: nil, **counters)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Changing the method signature to this causes several of the tests to fail.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Mentions updated_at: true

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Better to name the var and send it along:

def increment_counter(counter_name, id, touch: nil)
  update_counters(id, { counter_name => 1 }.merge(touch: touch)
end

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Note that this mehtod now raises if a counter without that id is not found. Probably a good thing.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'd write it as:

touch_time = Time.now
timestamps = resolve_timestamp_columns(find(id), touch) # Note the expected KW arg use.
timestamps.map do |column|
  updates << "#{connection.quote_column_name(column.to_s)} = '#{touch_time}'"
end

For MySQL we track columns with millisecond precision if it's configured right, so I think we must capture the touch time. Also we needn't bother with DateTime, Active Record should typecast it properly besides we'd need a require "date" at the top of the file here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why is the column quoted with double quotes, while the value uses singular? Doesn't column quoting use backticks too?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Needs to use touch: true

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'd go with:

touch_time = Time.now
resolve_timestamp_columns(object, touch).map do |column|
  updates[column] = touch_time
end

Alternatively, we could return a hash and go with:

# Here:
unscoped.where(primary_key => object.id).update_all(
  updates.merge(touch_updates(object, touch))
)

# In `update_counters`:
touch_updates(object, touch).map do |column, touch_time|
  updates << %(#{connection.quote_column_name(column.to_s)} = "#{touch_time}")
end

def touch_updates(object, touch)
  touch = object.timestamp_attributes_for_updates_in_model if touch == true
  touch_time = Time.now
  Array(touch).map { |column| [ column, touch_time ] }.to_h
end

@jtrost

jtrost commented Dec 28, 2016

Copy link
Copy Markdown
Contributor Author

@kaspth Sorry it took me so long to get around to this. I've updated the branch with the suggestions from your code review. There were two items that I had issues with, and I left replies to your comments. I worked on this on and off over the past several days, so if I missed something please let me know.

@rafaelfranca rafaelfranca left a comment

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.

Thank you for the pull request. I made some comments about the implementation.

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.

This should be using current_time_from_proper_timezone

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.

This should be using current_time_from_proper_timezone

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.

This method is now doing a query even when touch is not passed. I think we should only do that if touch is provided.

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.

There are trailing spaces here.

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.

This method should be indented one more level.

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.

When touch is false it is trying to update it as a column. We should handle this case properly.

@jtrost

jtrost commented Dec 29, 2016

Copy link
Copy Markdown
Contributor Author

@rafaelfranca I've resolved all of the issues from your review.

@kaspth kaspth left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Almost there! Squash your commits once the latest review has been implemented and then I think it's merge time. 😄

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Think it's odd we split out the timestamp handling to two places. Consider moving it like so:

touch = counters.delete(:touch)

updates = counters.map # …

if touch
  object = find(id)
  touch_time = object.send(:current_time_from_proper_timezone)
  resolve_timestamp_columns(object, touch).each do |column|
    updates << "#{connection.quote_column_name(column.to_s)} = '#{touch_time}'"
  end
end

Spares the local variable and also fixes the timestamps.map to use each :)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Let's borrow the documentation from increment_counter:

# * <tt>:touch</tt> option - Touch timestamp columns when updating.
#   Pass +true+ to touch +updated_at+ and/or +updated_on+. Pass a symbol to
#   touch that column or an array of symbols to touch just those ones.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

timestamp_attributes_for_updates_in_model is private, so I'd rather we said +updated_at+ and/or +updated_on+ like elsewhere 😁

@jtrost
jtrost force-pushed the counter-cache-updated-at branch from 160de74 to 1a8a9f0 Compare December 29, 2016 19:46
@jtrost

jtrost commented Dec 29, 2016

Copy link
Copy Markdown
Contributor Author

I've made the changes from the latest review, and squashed my commits into one commit.

@kaspth

kaspth commented Dec 29, 2016

Copy link
Copy Markdown
Contributor

Going to merge if/when the tests pass. @jtrost lovely work on this! ♥️

@kaspth

kaspth commented Dec 29, 2016

Copy link
Copy Markdown
Contributor

@jtrost looks like there's some failures in the mysql tests 😄

@kaspth kaspth assigned kaspth and unassigned rafaelfranca Dec 29, 2016

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.

Looks like we cannot use update_counters to the column named touch.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ActiveRecord::Callbacks defines #touch, so if you have a column named touch then it will raise ActiveRecord::DangerousAttributeError.

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.

Oh... you are right, thank you for your explanation!

@jtrost

jtrost commented Dec 30, 2016

Copy link
Copy Markdown
Contributor Author

@kaspth Some of the builds have failing tests with:

ActiveRecord::StatementInvalid: Mysql2::Error: Incorrect datetime value: '2016-12-29 20:03:55 UTC' for column 'updated_at' at row 1: UPDATE `topics` SET `replies_count` = COALESCE(`replies_count`, 0) - 1, `updated_at` = '2016-12-29 20:03:55 UTC', `written_on` = '2016-12-29 20:03:55 UTC' WHERE `topics`.`id` = 1

The updated_at value comes from current_time_from_proper_timezone. Do you know why the value returned from that method would be causing this error?

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.

Should be the below:

          resolve_timestamp_columns(object, touch).each do |column|
            updates << "#{connection.quote_column_name(column.to_s)} = #{connection.quote(touch_time)}"
          end

@kaspth

kaspth commented Dec 30, 2016

Copy link
Copy Markdown
Contributor

@jtrost looks like Travis isn't rerunning the build because it can't be merged. Can you rebase on latest master and squash your commits? (Just rebase out mine from yesterday.)

@jtrost
jtrost force-pushed the counter-cache-updated-at branch from 0f6dfab to 2e70cd1 Compare December 30, 2016 22:02
@kaspth

kaspth commented Dec 31, 2016

Copy link
Copy Markdown
Contributor

Strange how these tests fail when the timestamp tests use the same assertions:

assert_not_equal @previously_updated_at, @developer.updated_at
.

Figure it might be MySQL not using precision(6) on the topics table (but it does so locally). It's possible Travis doesn't support that level of precision, but then why do the timestamp tests pass?

Another option is that the _counters methods are simply too fast, but I doubt that.

@kaspth

kaspth commented Jan 1, 2017 •

Copy link
Copy Markdown
Contributor

@jtrost I fixed the tests and applied some more fixes — you've been through the ringer enough! 😄

Thanks so much for helping out with this, I think it's a great feature to have ❤️

bf77e641ce807857fcf804250c4f8ce817ae66be^...19deeb0

kamipo added a commit that referenced this pull request Jun 18, 2018
…thod

`touch` option was added to `increment!` (#27660) and `update_counters`
(#26995). But that option behaves inconsistently with
`Persistence#touch` method.

If `touch` option is passed attribute names, it won't update
update_at/on attributes unlike `Persistence#touch` method.

Due to changed from `Persistence#touch` to `increment!` with `touch`
option, #31405 has a regression that `counter_cache` with `touch` option
which is passed attribute names won't update update_at/on attributes.

I think that the inconsistency is not intended. To get back consistency,
ensure that `touch` option updates update_at/on attributes.
kamipo added a commit to kamipo/rails that referenced this pull request Jun 18, 2018
…thod

`touch` option was added to `increment!` (rails#27660) and `update_counters`
(rails#26995). But that option behaves inconsistently with
`Persistence#touch` method.

If `touch` option is passed attribute names, it won't update
update_at/on attributes unlike `Persistence#touch` method.

Due to changed from `Persistence#touch` to `increment!` with `touch`
option, rails#31405 has a regression that `counter_cache` with `touch` option
which is passed attribute names won't update update_at/on attributes.

I think that the inconsistency is not intended. To get back consistency,
ensure that `touch` option updates update_at/on attributes.
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.

ActiveRecord::CounterCache methods should have an option to change updated_at

7 participants