active_record-atomic_counters 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/MIT-LICENSE +20 -0
- data/README.md +209 -0
- data/Rakefile +11 -0
- data/lib/active_record/atomic_counters/counter_cache.rb +49 -0
- data/lib/active_record/atomic_counters/version.rb +8 -0
- data/lib/active_record/atomic_counters.rb +248 -0
- metadata +64 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 5948d2312207a8e174b11f1f679c846072e290845ada1db9099afa70f7ca4d49
|
|
4
|
+
data.tar.gz: 88b39412b47c0ccb7e3150672538c6bab94645f844efb329d9d5b251152bd4d2
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 19533cd6caa601a225cf68ce12c3a3fea66c77f700b4322cf2aa78f73f405e0aed2b1a610df78567e7e4f6f6f919a1c28f92258ee403f0df4fb024dfc6ea6d35
|
|
7
|
+
data.tar.gz: 929228a0056b9b8a7e86e3e86a2250f46773a5127e4d49fa54d9f8a5ed22b26b1e22ada867b45c2cea14e5c3ccb675d51f372bf9e513419a225a2978c43680db
|
data/MIT-LICENSE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
Copyright 2026 Minty Fresh
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
4
|
+
a copy of this software and associated documentation files (the
|
|
5
|
+
"Software"), to deal in the Software without restriction, including
|
|
6
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
7
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
8
|
+
permit persons to whom the Software is furnished to do so, subject to
|
|
9
|
+
the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be
|
|
12
|
+
included in all copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
17
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
18
|
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
19
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
20
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
# ActiveRecord::AtomicCounters
|
|
2
|
+
|
|
3
|
+
Increments and decrements counters of ActiveRecord records in the database atomically, and returns their new values.
|
|
4
|
+
|
|
5
|
+
## Why?
|
|
6
|
+
|
|
7
|
+
Rails' `increment!` updates the counter in the database atomically, but assigns the record its value in memory plus the
|
|
8
|
+
increment. If the counter was changed elsewhere since the record was loaded, the record's value is stale, so it can't
|
|
9
|
+
be relied on to decide what to do next. Reloading the record afterwards doesn't help either, since the counter may have
|
|
10
|
+
changed again between the UPDATE and the reload.
|
|
11
|
+
|
|
12
|
+
`atomic_increment` returns the value the UPDATE itself stored (with `RETURNING`), in the same statement, so each
|
|
13
|
+
increment sees exactly the value it produced, even when many happen at once.
|
|
14
|
+
|
|
15
|
+
### Enforcing a limit
|
|
16
|
+
|
|
17
|
+
Two customers buy a product with one available (`available_count: 1, purchased_count: 0`) at the same time, each
|
|
18
|
+
incrementing `purchased_count`. With `increment!`, both records see `purchased_count` as 1 (their loaded value of 0,
|
|
19
|
+
plus 1), so both purchases go through and the product is oversold (with 2 in the database). With `atomic_increment`,
|
|
20
|
+
the second increment sees 2, raises, and its transaction rolls the increment back:
|
|
21
|
+
|
|
22
|
+
```ruby
|
|
23
|
+
product.transaction do
|
|
24
|
+
product.atomic_increment(:purchased_count, 1)
|
|
25
|
+
|
|
26
|
+
product.purchased_count <= product.available_count or
|
|
27
|
+
raise Product::NoLongerAvailable, product
|
|
28
|
+
|
|
29
|
+
product.purchases.create!(customer:)
|
|
30
|
+
end
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### Numbering a sequence
|
|
34
|
+
|
|
35
|
+
Each value is returned to exactly one increment, so it can be used as a unique number without a retry on a unique index
|
|
36
|
+
violation. It's gapless too (unlike a database sequence), since a rolled back increment is undone, and its number reused:
|
|
37
|
+
|
|
38
|
+
```ruby
|
|
39
|
+
account.transaction do
|
|
40
|
+
number = account.atomic_increment(:invoices_count)
|
|
41
|
+
account.invoices.create!(number:)
|
|
42
|
+
end
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### Acting once on a milestone
|
|
46
|
+
|
|
47
|
+
Exactly one increment produces each value, so exactly one request reaches a milestone:
|
|
48
|
+
|
|
49
|
+
```ruby
|
|
50
|
+
if post.atomic_increment(:likes_count) == 1_000
|
|
51
|
+
PostMailer.with(post:).thousand_likes.deliver_later
|
|
52
|
+
end
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### Quotas, without loading records
|
|
56
|
+
|
|
57
|
+
The class methods return the new values by id, without loading the records first:
|
|
58
|
+
|
|
59
|
+
```ruby
|
|
60
|
+
requests = ApiKey.atomic_increment_counter(:requests_count, api_key_id)
|
|
61
|
+
head :too_many_requests if requests > ApiKey::REQUEST_LIMIT
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Installation
|
|
65
|
+
|
|
66
|
+
Add this line to your application's Gemfile:
|
|
67
|
+
|
|
68
|
+
```ruby
|
|
69
|
+
gem 'active_record-atomic_counters'
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
And then execute:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
$ bundle
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Then include `ActiveRecord::AtomicCounters` in your models (typically in `ApplicationRecord`, so all models get it):
|
|
79
|
+
|
|
80
|
+
```ruby
|
|
81
|
+
class ApplicationRecord < ActiveRecord::Base
|
|
82
|
+
primary_abstract_class
|
|
83
|
+
|
|
84
|
+
include ActiveRecord::AtomicCounters
|
|
85
|
+
end
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Usage
|
|
89
|
+
|
|
90
|
+
`atomic_increment` increments a counter in the database, and returns its new value (which is also assigned to the
|
|
91
|
+
record, without leaving it changed):
|
|
92
|
+
|
|
93
|
+
```ruby
|
|
94
|
+
post = Post.find(...) # views_count: 10
|
|
95
|
+
|
|
96
|
+
post.atomic_increment(:views_count) # => 11
|
|
97
|
+
post.atomic_increment(:views_count, 5) # => 16
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
```sql
|
|
101
|
+
UPDATE "posts" SET "views_count" = COALESCE("posts"."views_count", 0) + 5
|
|
102
|
+
WHERE "posts"."id" = 1 RETURNING "views_count"
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`atomic_decrement` decrements a counter in the same way:
|
|
106
|
+
|
|
107
|
+
```ruby
|
|
108
|
+
product.atomic_decrement(:stock, 2) # => 8
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
The changes to the counter (and touched timestamps) are recorded as the record's saved changes, as a save would:
|
|
112
|
+
|
|
113
|
+
```ruby
|
|
114
|
+
post.atomic_increment(:views_count) # => 11
|
|
115
|
+
post.saved_change_to_views_count # => [10, 11]
|
|
116
|
+
post.previous_changes # => { "views_count" => [10, 11] }
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Callbacks and validations are skipped, and unsaved changes to the record's other attributes are kept
|
|
120
|
+
(as unsaved changes, rather than recorded as saved).
|
|
121
|
+
Unsaved changes to the counter itself are discarded, in favour of its value in the database.
|
|
122
|
+
`ActiveRecord::RecordNotFound` is raised if the record no longer exists.
|
|
123
|
+
|
|
124
|
+
New records are incremented in memory, without saving them (as `increment` would).
|
|
125
|
+
|
|
126
|
+
### Touch
|
|
127
|
+
|
|
128
|
+
As with `update_counters`, timestamps aren't touched unless given `touch`: `true` touches the record's timestamps,
|
|
129
|
+
and a symbol or array touches the given attributes along with them:
|
|
130
|
+
|
|
131
|
+
```ruby
|
|
132
|
+
post.atomic_increment(:views_count, touch: true)
|
|
133
|
+
post.atomic_increment(:views_count, touch: :viewed_at)
|
|
134
|
+
post.atomic_increment(:views_count, touch: %i[viewed_at indexed_at])
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### Class methods
|
|
138
|
+
|
|
139
|
+
`atomic_increment_counter`, `atomic_decrement_counter` and `atomic_update_counters` update counters by id
|
|
140
|
+
(as `increment_counter`, `decrement_counter` and `update_counters` would), and return their new values:
|
|
141
|
+
|
|
142
|
+
```ruby
|
|
143
|
+
Post.atomic_increment_counter(:views_count, 1) # => 11
|
|
144
|
+
Post.atomic_decrement_counter(:views_count, 1, by: 2) # => 9
|
|
145
|
+
Post.atomic_update_counters(1, views_count: 1, shares_count: -1)
|
|
146
|
+
# => { "views_count" => 10, "shares_count" => 3 }
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
Given an array of ids (an array of arrays, with a composite primary key), they return the new values by id:
|
|
150
|
+
|
|
151
|
+
```ruby
|
|
152
|
+
Post.atomic_increment_counter(:views_count, [1, 2])
|
|
153
|
+
# => { 1 => 11, 2 => 4 }
|
|
154
|
+
|
|
155
|
+
Post.atomic_update_counters([1, 2], views_count: 1)
|
|
156
|
+
# => { 1 => { "views_count" => 12 }, 2 => { "views_count" => 5 } }
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
They return nil for ids which don't exist (rather than raising), skip default scopes, and take `touch` in the same
|
|
160
|
+
way:
|
|
161
|
+
|
|
162
|
+
```ruby
|
|
163
|
+
Post.atomic_increment_counter(:views_count, 1, touch: true)
|
|
164
|
+
Post.atomic_update_counters(1, views_count: 1, touch: :viewed_at)
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
### Counter caches
|
|
168
|
+
|
|
169
|
+
Rails updates counter caches (`belongs_to ..., counter_cache: true`) atomically in the database, but assigns the records
|
|
170
|
+
it updates their counters' values in memory plus the increment, which are stale if the counters were changed elsewhere
|
|
171
|
+
since the records were loaded. Counter caches can assign the counters' new values from the database instead:
|
|
172
|
+
|
|
173
|
+
```ruby
|
|
174
|
+
# config/application.rb
|
|
175
|
+
config.active_record.atomic_counter_cache = true
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
```ruby
|
|
179
|
+
post = Post.find(...) # comments_count: 0
|
|
180
|
+
Comment.create!(post: Post.find(...)) # another process adds a comment (comments_count: 1)
|
|
181
|
+
Comment.create!(post:)
|
|
182
|
+
|
|
183
|
+
post.comments_count # => 2 (rather than 1)
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
This applies wherever Rails updates a counter cache through a loaded record (eg. creating or destroying a record with
|
|
187
|
+
its `belongs_to` association loaded, or deleting records through a `has_many` association), for models which include
|
|
188
|
+
`ActiveRecord::AtomicCounters`. As with Rails, the record's saved changes are left as they were, and records which no
|
|
189
|
+
longer exist are skipped (rather than raising).
|
|
190
|
+
|
|
191
|
+
### Databases
|
|
192
|
+
|
|
193
|
+
The new values are returned from the UPDATE itself (with `RETURNING`), so PostgreSQL or SQLite is required.
|
|
194
|
+
|
|
195
|
+
## Development
|
|
196
|
+
|
|
197
|
+
The specs run against a dummy Rails application in `spec/dummy`, using SQLite by default:
|
|
198
|
+
|
|
199
|
+
```bash
|
|
200
|
+
$ bin/rspec
|
|
201
|
+
$ bin/rubocop
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
PostgreSQL is selected with the `DATABASE_ADAPTER` and `DATABASE_URL` environment variables
|
|
205
|
+
(see `.github/workflows/ci.yml`).
|
|
206
|
+
|
|
207
|
+
## License
|
|
208
|
+
|
|
209
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
data/Rakefile
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# typed: true
|
|
2
|
+
# frozen_string_literal: true
|
|
3
|
+
|
|
4
|
+
module ActiveRecord
|
|
5
|
+
# Whether counter caches assign the new values of counters from the database (with RETURNING) to loaded records.
|
|
6
|
+
# Otherwise `increment!` updates the counters in the database by the increment, but assigns the records their
|
|
7
|
+
# counters' values in memory plus the increment (which are stale if the counters were changed elsewhere).
|
|
8
|
+
# Set by `config.active_record.atomic_counter_cache`. Applies to models which include `ActiveRecord::AtomicCounters`.
|
|
9
|
+
singleton_class.attr_accessor :atomic_counter_cache
|
|
10
|
+
self.atomic_counter_cache = false
|
|
11
|
+
|
|
12
|
+
module AtomicCounters
|
|
13
|
+
# Counter caches are updated in the database by the associations which cache them, through their loaded records
|
|
14
|
+
# (with `increment!`) where they have them, or otherwise by id (without assigning the counters to any records).
|
|
15
|
+
# The updates through loaded records are replaced, where enabled (see `ActiveRecord.atomic_counter_cache`).
|
|
16
|
+
module CounterCache
|
|
17
|
+
# Updates the counter cache of the record which the record belongs to, when the record is created or destroyed.
|
|
18
|
+
module BelongsToAssociation
|
|
19
|
+
private
|
|
20
|
+
|
|
21
|
+
#: (Integer by) -> void
|
|
22
|
+
def update_counters(by)
|
|
23
|
+
return super unless ActiveRecord.atomic_counter_cache && require_counter_update? && foreign_key_present?
|
|
24
|
+
return super unless target.respond_to?(:_atomic_increment_counter_cache) && !stale_target?
|
|
25
|
+
|
|
26
|
+
target._atomic_increment_counter_cache(reflection.counter_cache_column, by, touch: reflection.options[:touch])
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# Updates the counter cache of the record which owns the records, when they're deleted from the association.
|
|
31
|
+
module HasManyAssociation
|
|
32
|
+
private
|
|
33
|
+
|
|
34
|
+
#: (Integer difference, ?ActiveRecord::Reflection::AssociationReflection reflection) -> void
|
|
35
|
+
def update_counter(difference, reflection = reflection())
|
|
36
|
+
return super unless ActiveRecord.atomic_counter_cache && reflection.has_cached_counter?
|
|
37
|
+
return super unless owner.respond_to?(:_atomic_increment_counter_cache)
|
|
38
|
+
|
|
39
|
+
owner._atomic_increment_counter_cache(reflection.counter_cache_column, difference, touch: nil)
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
ActiveSupport.on_load(:active_record) do
|
|
47
|
+
ActiveRecord::Associations::BelongsToAssociation.prepend(ActiveRecord::AtomicCounters::CounterCache::BelongsToAssociation)
|
|
48
|
+
ActiveRecord::Associations::HasManyAssociation.prepend(ActiveRecord::AtomicCounters::CounterCache::HasManyAssociation)
|
|
49
|
+
end
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
# typed: true
|
|
2
|
+
# frozen_string_literal: true
|
|
3
|
+
|
|
4
|
+
require 'active_record'
|
|
5
|
+
require 'active_record/atomic_counters/version'
|
|
6
|
+
require 'active_record/atomic_counters/counter_cache'
|
|
7
|
+
|
|
8
|
+
module ActiveRecord
|
|
9
|
+
# Increments and decrements counters of records in the database atomically, returning their new values
|
|
10
|
+
# (eg. to number the records of a sequence, or to act on reaching a limit):
|
|
11
|
+
#
|
|
12
|
+
# class ApplicationRecord < ActiveRecord::Base
|
|
13
|
+
# include ActiveRecord::AtomicCounters
|
|
14
|
+
# end
|
|
15
|
+
#
|
|
16
|
+
# post.atomic_increment(:views_count) # => 11
|
|
17
|
+
# post.atomic_decrement(:stock, 2, touch: :restocked_at) # => 8
|
|
18
|
+
#
|
|
19
|
+
# Post.atomic_increment_counter(:views_count, 1) # => 12
|
|
20
|
+
# Post.atomic_update_counters([1, 2], views_count: 1) # => { 1 => { "views_count" => 13 }, 2 => ... }
|
|
21
|
+
module AtomicCounters
|
|
22
|
+
extend ActiveSupport::Concern
|
|
23
|
+
|
|
24
|
+
class_methods do
|
|
25
|
+
# Updates the counters of the records with the given ids in the database by the given amounts (as
|
|
26
|
+
# `update_counters` does, including its `touch` option), and returns their new values: `{ counter => value }`
|
|
27
|
+
# for one id, or `{ id => { counter => value } }` for an array of ids (an array of arrays, with a composite
|
|
28
|
+
# primary key), keyed by the ids as given. Returns nil for ids which don't exist.
|
|
29
|
+
#
|
|
30
|
+
#: (untyped id, Hash[Symbol | String, untyped] counters) -> Hash[untyped, untyped]?
|
|
31
|
+
def atomic_update_counters(id, counters)
|
|
32
|
+
counters = counters.stringify_keys
|
|
33
|
+
touch = counters.delete('touch')
|
|
34
|
+
counters = counters.to_h { |counter, by| [atomic_counter_attribute_name(counter), by] }
|
|
35
|
+
|
|
36
|
+
ids, many = atomic_counter_ids(id)
|
|
37
|
+
relation = unscoped.where(primary_key => ids)
|
|
38
|
+
rows = ids.empty? ? [] : _atomic_update_counters(relation, counters, atomic_counter_touch_attributes(touch))
|
|
39
|
+
values = atomic_counter_values_by_id(ids, rows, counters.keys)
|
|
40
|
+
|
|
41
|
+
many ? values : values[id]
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# Increments a counter of the records with the given ids in the database by `by`, and returns its new values
|
|
45
|
+
# (see `atomic_update_counters`): the new value for one id, or `{ id => value }` for an array of ids.
|
|
46
|
+
#
|
|
47
|
+
#: (Symbol | String counter, untyped id, ?by: Numeric, ?touch: bool | Symbol | Array[Symbol] | nil) -> untyped
|
|
48
|
+
def atomic_increment_counter(counter, id, by: 1, touch: nil)
|
|
49
|
+
values = atomic_update_counters(id, { counter => by, touch: })
|
|
50
|
+
name = atomic_counter_attribute_name(counter)
|
|
51
|
+
|
|
52
|
+
_ids, many = atomic_counter_ids(id)
|
|
53
|
+
many ? values&.transform_values { |counters| counters&.fetch(name) } : values&.fetch(name)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Decrements a counter of the records with the given ids in the database by `by`, and returns its new values
|
|
57
|
+
# (see `atomic_increment_counter`).
|
|
58
|
+
#
|
|
59
|
+
#: (Symbol | String counter, untyped id, ?by: Numeric, ?touch: bool | Symbol | Array[Symbol] | nil) -> untyped
|
|
60
|
+
def atomic_decrement_counter(counter, id, by: 1, touch: nil)
|
|
61
|
+
atomic_increment_counter(counter, id, by: -by, touch:)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# Updates the counters of the records matching the relation, and returns their primary keys and the new
|
|
65
|
+
# values of the counters (with UPDATE ... RETURNING).
|
|
66
|
+
#
|
|
67
|
+
#: (ActiveRecord::Relation relation, Hash[String, Numeric] counters, Hash[String, Time] touch_attributes)
|
|
68
|
+
#| -> Array[Hash[String, untyped]]
|
|
69
|
+
def _atomic_update_counters(relation, counters, touch_attributes) # :nodoc:
|
|
70
|
+
columns = Array(primary_key) | counters.keys
|
|
71
|
+
statement = build_atomic_counters_statement(relation, counters, touch_attributes)
|
|
72
|
+
|
|
73
|
+
result = with_connection do |connection|
|
|
74
|
+
sql = connection.unprepared_statement { connection.to_sql(statement) }
|
|
75
|
+
sql = "#{sql} RETURNING #{columns.map { |column| connection.quote_column_name(column) }.join(', ')}"
|
|
76
|
+
|
|
77
|
+
connection.exec_query(sql, "#{name} Atomic Update Counters")
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
result.rows.map do |row|
|
|
81
|
+
columns.zip(row).to_h { |column, value| [column, type_for_attribute(column).deserialize(value)] }
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
private
|
|
86
|
+
|
|
87
|
+
#: (Symbol | String counter) -> String
|
|
88
|
+
def atomic_counter_attribute_name(counter)
|
|
89
|
+
name = attribute_aliases[counter.to_s] || counter.to_s
|
|
90
|
+
has_attribute?(name) or raise ActiveModel::MissingAttributeError, "can't increment unknown attribute `#{name}`"
|
|
91
|
+
|
|
92
|
+
name
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
# As `update_counters` does, an array is many ids (an array of arrays, with a composite primary key).
|
|
96
|
+
#
|
|
97
|
+
#: (untyped id) -> [Array[untyped], bool]
|
|
98
|
+
def atomic_counter_ids(id)
|
|
99
|
+
many = composite_primary_key? ? id.is_a?(Array) && id.first.is_a?(Array) : id.is_a?(Array)
|
|
100
|
+
|
|
101
|
+
[many ? id : [id], many]
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# Keys the counters of the updated rows by the ids as given, with nil for ids which weren't updated.
|
|
105
|
+
#
|
|
106
|
+
#: (Array[untyped] ids, Array[Hash[String, untyped]] rows, Array[String] counters)
|
|
107
|
+
#| -> Hash[untyped, Hash[String, untyped]?]
|
|
108
|
+
def atomic_counter_values_by_id(ids, rows, counters)
|
|
109
|
+
primary_key = Array(self.primary_key)
|
|
110
|
+
values_by_id = rows.to_h { |row| [row.values_at(*primary_key), row.slice(*counters)] }
|
|
111
|
+
|
|
112
|
+
ids.index_with { |id| values_by_id[atomic_counter_cast_id(id)] }
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
# Casts an id as given to match the primary key read from the database (eg. "1" to 1).
|
|
116
|
+
#
|
|
117
|
+
#: (untyped id) -> Array[untyped]
|
|
118
|
+
def atomic_counter_cast_id(id)
|
|
119
|
+
Array(primary_key).zip(Array(id)).map { |column, value| type_for_attribute(column).cast(value) }
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
#: (bool | Symbol | Array[Symbol] | nil touch) -> Hash[String, Time]
|
|
123
|
+
def atomic_counter_touch_attributes(touch)
|
|
124
|
+
return {} unless touch
|
|
125
|
+
|
|
126
|
+
touch_attributes_with_time(*(touch == true ? [] : Array(touch)))
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
# Updates counters from 0 if they're NULL, as `update_counters` does.
|
|
130
|
+
#
|
|
131
|
+
#: (ActiveRecord::Relation relation, Hash[String, Numeric] counters, Hash[String, Time] touch_attributes)
|
|
132
|
+
#| -> Arel::UpdateManager
|
|
133
|
+
def build_atomic_counters_statement(relation, counters, touch_attributes)
|
|
134
|
+
assignments = counters.map { |counter, by| [arel_table[counter], atomic_counter_increment(counter, by)] }
|
|
135
|
+
touch_attributes.each do |attribute, time|
|
|
136
|
+
assignments << [arel_table[attribute], predicate_builder.build_bind_attribute(attribute, time)]
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
statement = Arel::UpdateManager.new(arel_table)
|
|
140
|
+
statement.set(assignments)
|
|
141
|
+
statement.wheres = relation.arel.constraints
|
|
142
|
+
statement
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
# As `update_counters` does, with the absolute value bound, for unsigned columns.
|
|
146
|
+
#
|
|
147
|
+
#: (String counter, Numeric by) -> Arel::Nodes::Node
|
|
148
|
+
def atomic_counter_increment(counter, by)
|
|
149
|
+
increment = predicate_builder.build_bind_attribute(counter, by.abs)
|
|
150
|
+
value = arel_table.coalesce(arel_table[counter], 0)
|
|
151
|
+
|
|
152
|
+
(by.negative? ? value - increment : value + increment).expr
|
|
153
|
+
end
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
# Increments a counter of the record in the database by `by`, and returns its new value (also assigned to the
|
|
157
|
+
# record). Unlike `increment!` (which assigns the record its value in memory plus the increment, which is stale if
|
|
158
|
+
# the counter was changed elsewhere), the value returned is the one stored by this increment.
|
|
159
|
+
#
|
|
160
|
+
# Timestamps aren't touched unless given `touch` (as `update_counters` takes it): the record's timestamps (`true`),
|
|
161
|
+
# or its timestamps along with the given attributes (a symbol or an array).
|
|
162
|
+
# Callbacks and validations are skipped, and unsaved changes to other attributes are kept.
|
|
163
|
+
# The changes are recorded as the record's saved changes (see `saved_changes`), as a save would.
|
|
164
|
+
# Raises `ActiveRecord::RecordNotFound` if the record no longer exists.
|
|
165
|
+
#
|
|
166
|
+
# New records are incremented in memory, without saving them (as `increment` would).
|
|
167
|
+
#
|
|
168
|
+
#: (Symbol | String counter, ?Numeric by, ?touch: bool | Symbol | Array[Symbol] | nil) -> Numeric
|
|
169
|
+
def atomic_increment(counter, by = 1, touch: nil)
|
|
170
|
+
model = self.class
|
|
171
|
+
name = model.send(:atomic_counter_attribute_name, counter)
|
|
172
|
+
return increment(name, by)[name] if new_record?
|
|
173
|
+
|
|
174
|
+
touch_attributes = model.send(:atomic_counter_touch_attributes, touch)
|
|
175
|
+
value = atomic_increment_in_database(name, by, touch_attributes)
|
|
176
|
+
|
|
177
|
+
value.nil? and raise RecordNotFound.new(
|
|
178
|
+
"Couldn't find #{model.name} with #{_query_constraints_hash.inspect}", model.name, model.primary_key, id
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
apply_atomic_counter_changes(name, by, value, touch_attributes)
|
|
182
|
+
_read_attribute(name)
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
# Decrements a counter of the record in the database by `by`, and returns its new value
|
|
186
|
+
# (see `atomic_increment`).
|
|
187
|
+
#
|
|
188
|
+
#: (Symbol | String counter, ?Numeric by, ?touch: bool | Symbol | Array[Symbol] | nil) -> Numeric
|
|
189
|
+
def atomic_decrement(counter, by = 1, touch: nil)
|
|
190
|
+
atomic_increment(counter, -by, touch:)
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
# Increments a counter cache of the record in the database (for `atomic_counter_cache`), assigning its new value
|
|
194
|
+
# and touched timestamps without leaving them changed. Unlike `atomic_increment`, its saved changes are left as
|
|
195
|
+
# they were (as `increment!` does), since counter caches are updated within the saves of other records (which may
|
|
196
|
+
# be within the record's own save, eg. by autosaving its associations). Does nothing if the record no longer
|
|
197
|
+
# exists (as `increment!` does).
|
|
198
|
+
#
|
|
199
|
+
#: (String counter, Numeric by, touch: bool | Symbol | Array[Symbol] | nil) -> void
|
|
200
|
+
def _atomic_increment_counter_cache(counter, by, touch:) # :nodoc:
|
|
201
|
+
return increment(counter, by) if new_record?
|
|
202
|
+
|
|
203
|
+
touch_attributes = self.class.send(:atomic_counter_touch_attributes, touch)
|
|
204
|
+
value = atomic_increment_in_database(counter, by, touch_attributes)
|
|
205
|
+
return if value.nil?
|
|
206
|
+
|
|
207
|
+
{ counter => value, **touch_attributes }.each do |attribute, attribute_value|
|
|
208
|
+
_write_attribute(attribute, attribute_value)
|
|
209
|
+
clear_attribute_change(attribute)
|
|
210
|
+
end
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
private
|
|
214
|
+
|
|
215
|
+
# Returns the new value of the counter, or nil if the record no longer exists.
|
|
216
|
+
#
|
|
217
|
+
#: (String name, Numeric by, Hash[String, Time] touch_attributes) -> untyped
|
|
218
|
+
def atomic_increment_in_database(name, by, touch_attributes)
|
|
219
|
+
model = self.class
|
|
220
|
+
relation = model.unscoped.where(_query_constraints_hash)
|
|
221
|
+
|
|
222
|
+
model._atomic_update_counters(relation, { name => by }, touch_attributes).first&.fetch(name)
|
|
223
|
+
end
|
|
224
|
+
|
|
225
|
+
# Assigns the updated attributes without leaving them changed, and records their changes as the record's
|
|
226
|
+
# saved changes (see `saved_changes`), as if only they had been saved. Unlike `changes_applied`,
|
|
227
|
+
# unsaved changes to other attributes are left unsaved (rather than recorded as saved, without having been saved).
|
|
228
|
+
#
|
|
229
|
+
#: (String name, Numeric by, untyped value, Hash[String, Time] touch_attributes) -> void
|
|
230
|
+
def apply_atomic_counter_changes(name, by, value, touch_attributes)
|
|
231
|
+
changes = { name => [value - by, value] }
|
|
232
|
+
touch_attributes.each { |attribute, time| changes[attribute] = [_read_attribute(attribute), time] }
|
|
233
|
+
|
|
234
|
+
saved_attributes = @attributes.map(&:forgetting_assignment)
|
|
235
|
+
|
|
236
|
+
changes.each do |attribute, (previous_value, new_value)|
|
|
237
|
+
saved_attributes[attribute] = saved_attributes[attribute].with_cast_value(previous_value).forgetting_assignment
|
|
238
|
+
saved_attributes.write_from_user(attribute, new_value)
|
|
239
|
+
|
|
240
|
+
_write_attribute(attribute, new_value)
|
|
241
|
+
clear_attribute_change(attribute)
|
|
242
|
+
end
|
|
243
|
+
|
|
244
|
+
# Read by `saved_changes`, `previous_changes` and `saved_change_to_attribute?` (see `ActiveModel::Dirty`)
|
|
245
|
+
@mutations_before_last_save = ActiveModel::AttributeMutationTracker.new(saved_attributes)
|
|
246
|
+
end
|
|
247
|
+
end
|
|
248
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: active_record-atomic_counters
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Minty Fresh
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies:
|
|
12
|
+
- !ruby/object:Gem::Dependency
|
|
13
|
+
name: activerecord
|
|
14
|
+
requirement: !ruby/object:Gem::Requirement
|
|
15
|
+
requirements:
|
|
16
|
+
- - ">="
|
|
17
|
+
- !ruby/object:Gem::Version
|
|
18
|
+
version: '8.1'
|
|
19
|
+
type: :runtime
|
|
20
|
+
prerelease: false
|
|
21
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
22
|
+
requirements:
|
|
23
|
+
- - ">="
|
|
24
|
+
- !ruby/object:Gem::Version
|
|
25
|
+
version: '8.1'
|
|
26
|
+
description: Increments and decrements counters of ActiveRecord records in the database,
|
|
27
|
+
atomically, and returns their new values.
|
|
28
|
+
email:
|
|
29
|
+
- 7896757+mintyfresh@users.noreply.github.com
|
|
30
|
+
executables: []
|
|
31
|
+
extensions: []
|
|
32
|
+
extra_rdoc_files: []
|
|
33
|
+
files:
|
|
34
|
+
- MIT-LICENSE
|
|
35
|
+
- README.md
|
|
36
|
+
- Rakefile
|
|
37
|
+
- lib/active_record/atomic_counters.rb
|
|
38
|
+
- lib/active_record/atomic_counters/counter_cache.rb
|
|
39
|
+
- lib/active_record/atomic_counters/version.rb
|
|
40
|
+
homepage: https://github.com/mintyfresh/active_record-atomic_counters
|
|
41
|
+
licenses:
|
|
42
|
+
- MIT
|
|
43
|
+
metadata:
|
|
44
|
+
homepage_uri: https://github.com/mintyfresh/active_record-atomic_counters
|
|
45
|
+
source_code_uri: https://github.com/mintyfresh/active_record-atomic_counters
|
|
46
|
+
rubygems_mfa_required: 'true'
|
|
47
|
+
rdoc_options: []
|
|
48
|
+
require_paths:
|
|
49
|
+
- lib
|
|
50
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
51
|
+
requirements:
|
|
52
|
+
- - ">="
|
|
53
|
+
- !ruby/object:Gem::Version
|
|
54
|
+
version: '3.2'
|
|
55
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
56
|
+
requirements:
|
|
57
|
+
- - ">="
|
|
58
|
+
- !ruby/object:Gem::Version
|
|
59
|
+
version: '0'
|
|
60
|
+
requirements: []
|
|
61
|
+
rubygems_version: 4.0.20
|
|
62
|
+
specification_version: 4
|
|
63
|
+
summary: Atomic counters for ActiveRecord records
|
|
64
|
+
test_files: []
|