amounts 0.3.0 → 0.3.1

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1bcdc8db0e926c26c1aa8c46d67056bc9c10a109cf9b9622ca747d4819506173
4
- data.tar.gz: d3cfb48d0f0d030ca3fa83df0f3a8a0d71bf11b19de5fe2b95870758c273caf2
3
+ metadata.gz: 1b99d7bc88a17f234c114154f19398ecc56df1543f06d4761a3575b94cdd048e
4
+ data.tar.gz: 066f2619c934bcda1f006a0c4bed2bda6afb9aa995e9158eec34186d84570b06
5
5
  SHA512:
6
- metadata.gz: 3cd1e9bb7282f1c8e7ca3f3f4c7b4ce431b3fdc818e9e21cb08943e332b9f47456b2388aa931c5ec62b311d94fe767167b0ea421111a72a667611575b407c315
7
- data.tar.gz: 6ef755ff9eb20f5da1f6ac948598a8a09186c160035adfe480ba93fc26dc314cf2f25fcbe841ecce9cc946a24542bef31f4f6e8b66c30176825cf6db24f3b80e
6
+ metadata.gz: f4911f3bff7b8a5af9b7d946845a4d264bacf29736f841767d9453622f2c344e3dc24dd2762e1b13965817cadebc4ae4c341e042b15174e2982437fdb6c76be1
7
+ data.tar.gz: 38979ea9efb87717a922271cb0acf64f80a9998af17ae01e0139789ad4662b99f88f82d1816844786ac9a133f83f7b01487bc7c1a1e24a09f91d48427641b72b
data/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.1 - 2026-11-15
4
+
5
+ ### Added
6
+
7
+ - `sum_amount`, `minimum_amount`, `maximum_amount` and `average_amount` take
8
+ several `has_amount` attributes and aggregate them all in one query, returning
9
+ a Hash by attribute name (per group when grouped) in place of each Amount, as
10
+ Rails' `pluck` returns rows for several columns. A model with several amounts
11
+ on one table no longer pays one round trip per amount over the same rows.
12
+ Each attribute folds exactly as it would alone, with the same symbol rule. With
13
+ several attributes, a group appears when it has any row, and an attribute with
14
+ no amount in it gets the empty-set result (zero for a fixed-symbol sum, else
15
+ `nil`). A name given twice raises `ArgumentError`. With one attribute, nothing
16
+ changes.
17
+
3
18
  ## 0.3.0 - 2026-11-15
4
19
 
5
20
  ### Added
data/README.md CHANGED
@@ -568,6 +568,14 @@ Holding.average_amount(:fee) # truncated toward zero, lik
568
568
  Holding.group(:amount_symbol).sum_amount(:amount) # => { "USDC" => #<Amount USDC ...>, "SOL" => ... }
569
569
  ```
570
570
 
571
+ Given several attributes, like `pluck`, each aggregate still runs one query and
572
+ returns a Hash by name:
573
+
574
+ ```ruby
575
+ Holding.sum_amount(:amount, :fee) # => { amount: #<Amount USDC ...>, fee: #<Amount SOL ...> }
576
+ Holding.group(:account_id).sum_amount(:amount, :fee) # => { 1 => { amount: ..., fee: ... }, ... }
577
+ ```
578
+
571
579
  Symbols never mix: a multi-symbol attribute with more than one symbol in scope
572
580
  (or in one group) raises `Amount::TypeMismatch`, so group by its symbol column for
573
581
  one Amount per symbol. A fixed-symbol sum over no rows is zero; otherwise an
@@ -11,6 +11,13 @@ class Amount
11
11
  # Group by a column or SQL expression; grouping by an association name
12
12
  # raises `ArgumentError` (group by its foreign key instead).
13
13
  #
14
+ # Given several attributes, like Rails' `pluck`, each method still runs
15
+ # one query and returns a Hash keyed by attribute name in place of each
16
+ # Amount: `{ quantity: ..., cost: ... }`, or per group
17
+ # `{ "search" => { quantity: ..., cost: ... } }`. A group is in the result
18
+ # when it has any row; an attribute with no amount in that group gets the
19
+ # result of an empty set (zero for a fixed-symbol sum, else `nil`).
20
+ #
14
21
  # Amounts of different symbols never combine: a multi-symbol attribute
15
22
  # with more than one symbol in scope, or in one group, raises
16
23
  # {Amount::TypeMismatch}. Group by its symbol column for one Amount per
@@ -20,65 +27,83 @@ class Amount
20
27
  # UsageRecord.sum_amount(:cost) # => #<Amount USDP ...>
21
28
  # UsageRecord.group(:kind).sum_amount(:cost) # => { "search" => #<Amount USDP ...> }
22
29
  # UsageRecord.group(:quantity_symbol).sum_amount(:quantity)
30
+ #
31
+ # @example Several attributes, one query
32
+ # UsageRecord.group(:kind).sum_amount(:quantity, :cost)
33
+ # # => { "search" => { quantity: #<Amount SEARCHES 3>, cost: #<Amount USDP $0.30> } }
23
34
  module Calculations
24
35
  # A fixed-symbol sum over no rows is zero; a multi-symbol one is `nil`.
25
36
  #
26
- # @param name [Symbol, String] a `has_amount` attribute
27
- # @return [Amount, Hash, nil]
37
+ # @param names [Array<Symbol, String>] one or more `has_amount` attributes
38
+ # @return [Amount, Hash, nil] for several names, a Hash by name
28
39
  # @raise [Amount::TypeMismatch] when amounts of more than one symbol meet
29
- def sum_amount(name)
40
+ # @raise [ArgumentError] for no names, or a name given twice
41
+ def sum_amount(*names)
30
42
  # SQL's SUM is NULL over no rows, and `none` runs no query at all;
31
43
  # Rails' `sum` is zero for both. `deserialize(0)` is that zero for a
32
44
  # fixed symbol and `nil` for a multi-symbol attribute.
33
- zero = amount_attribute_definitions.fetch(name.to_sym).type.deserialize(0)
34
- aggregate_amount(name, :sum) { |sum| sum || zero } || zero
45
+ aggregate_amounts(names, :sum) { |definition, sum| sum || definition.type.deserialize(0) }
35
46
  end
36
47
 
37
- # @param name [Symbol, String] a `has_amount` attribute
38
- # @return [Amount, Hash, nil] `nil` over no rows
48
+ # @param names [Array<Symbol, String>] one or more `has_amount` attributes
49
+ # @return [Amount, Hash, nil] `nil` over no rows; for several names, a Hash by name
39
50
  # @raise [Amount::TypeMismatch] when amounts of more than one symbol meet
40
- def minimum_amount(name)
41
- aggregate_amount(name, :minimum) { |minimum| minimum }
51
+ # @raise [ArgumentError] for no names, or a name given twice
52
+ def minimum_amount(*names)
53
+ aggregate_amounts(names, :minimum) { |_definition, minimum| minimum }
42
54
  end
43
55
 
44
- # @param name [Symbol, String] a `has_amount` attribute
45
- # @return [Amount, Hash, nil] `nil` over no rows
56
+ # @param names [Array<Symbol, String>] one or more `has_amount` attributes
57
+ # @return [Amount, Hash, nil] `nil` over no rows; for several names, a Hash by name
46
58
  # @raise [Amount::TypeMismatch] when amounts of more than one symbol meet
47
- def maximum_amount(name)
48
- aggregate_amount(name, :maximum) { |maximum| maximum }
59
+ # @raise [ArgumentError] for no names, or a name given twice
60
+ def maximum_amount(*names)
61
+ aggregate_amounts(names, :maximum) { |_definition, maximum| maximum }
49
62
  end
50
63
 
51
64
  # The sum divided by the number of amounts, truncated toward zero to a
52
65
  # whole atomic unit, as `Amount#/` does. The sum and the count come from
53
66
  # the same query.
54
67
  #
55
- # @param name [Symbol, String] a `has_amount` attribute
56
- # @return [Amount, Hash, nil] `nil` over no rows
68
+ # @param names [Array<Symbol, String>] one or more `has_amount` attributes
69
+ # @return [Amount, Hash, nil] `nil` over no rows; for several names, a Hash by name
57
70
  # @raise [Amount::TypeMismatch] when amounts of more than one symbol meet
58
- def average_amount(name)
59
- aggregate_amount(name, :sum, :count) { |sum, count| sum / count unless count.zero? }
71
+ # @raise [ArgumentError] for no names, or a name given twice
72
+ def average_amount(*names)
73
+ aggregate_amounts(names, :sum, :count) { |_definition, sum, count| sum / count unless count.zero? }
60
74
  end
61
75
 
62
76
  private
63
77
 
64
- # Plucks the caller's groups, the symbol and the aggregates as
65
- # `[*groups, symbol, atomic, *rest]`, then yields each group's first
66
- # aggregate as an Amount, with the rest as they came.
67
- def aggregate_amount(name, *operations)
68
- definition = amount_attribute_definitions.fetch(name.to_sym)
78
+ # Plucks `[*groups, *columns]`, where each attribute contributes its
79
+ # symbol and one aggregate per operation, then folds each caller group's
80
+ # rows per attribute. A multi-symbol attribute is grouped by its symbol
81
+ # column too, so one caller group can span several rows.
82
+ def aggregate_amounts(names, *operations, &fold)
83
+ definitions = amount_definitions_for(names)
69
84
  groups = amount_group_values
70
- atomic = arel_table[definition.atomic_column]
85
+ rows = amount_aggregate_scope(definitions)
86
+ .pluck(*groups, *amount_aggregate_columns(definitions, operations))
87
+
88
+ fold_rows = lambda do |group_rows|
89
+ columns = group_rows.map { |row| row.drop(groups.size) }
90
+ results = amount_fold_group(definitions, operations, columns, &fold)
91
+ names.one? ? results.values.first : results
92
+ end
93
+
94
+ return fold_rows.call(rows) if groups.empty?
71
95
 
72
- rows = amount_aggregate_scope(definition)
73
- .pluck(*groups, amount_symbol_select(definition),
74
- *operations.map { |operation| atomic.public_send(operation) })
96
+ rows.group_by { |row| amount_group_key(row.first(groups.size)) }.transform_values(&fold_rows)
97
+ end
98
+
99
+ def amount_definitions_for(names)
100
+ raise ArgumentError, "pass at least one has_amount attribute" if names.empty?
75
101
 
76
- results = rows.group_by { |row| amount_group_key(row.first(groups.size)) }
77
- .transform_values do |group_rows|
78
- yield(*amount_group_values_of(definition, group_rows.map { |row| row.drop(groups.size) }))
79
- end
102
+ symbols = names.map(&:to_sym)
103
+ repeated = symbols.detect { |symbol| symbols.count(symbol) > 1 }
104
+ raise ArgumentError, "#{repeated} is given more than once" if repeated
80
105
 
81
- groups.empty? ? results[[]] : results
106
+ symbols.map { |symbol| amount_attribute_definitions.fetch(symbol) }
82
107
  end
83
108
 
84
109
  # The caller passed these to `group`, which takes raw SQL; `pluck` takes
@@ -95,12 +120,27 @@ class Amount
95
120
  end
96
121
  end
97
122
 
98
- # A multi-symbol attribute is grouped by its symbol too, so each row is
99
- # one symbol's aggregate. Rows without an amount are left out.
100
- def amount_aggregate_scope(definition)
101
- return all if definition.fixed_symbol?
123
+ # Each multi-symbol attribute is grouped by its symbol column, so each
124
+ # row holds one symbol per attribute. A single multi-symbol attribute
125
+ # also leaves out rows without an amount, so a group with no amount is
126
+ # absent rather than `nil`; with several attributes a row may have one
127
+ # amount and not another, and the fold skips each attribute's `NULL`s.
128
+ def amount_aggregate_scope(definitions)
129
+ multi_symbol = definitions.reject(&:fixed_symbol?)
130
+ scope = all
131
+ scope = scope.where.not(multi_symbol.first.symbol_column => nil) if definitions.one? && multi_symbol.one?
132
+
133
+ multi_symbol.reduce(scope) { |grouped, definition| grouped.group(definition.symbol_column) }
134
+ end
102
135
 
103
- where.not(definition.symbol_column => nil).group(definition.symbol_column)
136
+ # Per attribute: its symbol (a constant for a fixed symbol), then one
137
+ # aggregate of its atomic column per operation.
138
+ def amount_aggregate_columns(definitions, operations)
139
+ definitions.flat_map do |definition|
140
+ atomic = arel_table[definition.atomic_column]
141
+
142
+ [amount_symbol_select(definition), *operations.map { |operation| atomic.public_send(operation) }]
143
+ end
104
144
  end
105
145
 
106
146
  def amount_symbol_select(definition)
@@ -113,14 +153,47 @@ class Amount
113
153
  values.size == 1 ? values.first : values
114
154
  end
115
155
 
116
- def amount_group_values_of(definition, rows)
117
- unless rows.size == 1
118
- raise ::Amount::TypeMismatch,
119
- "#{definition.name} has more than one symbol in scope: #{rows.map(&:first).join(', ')}"
156
+ # One caller group's rows, folded per attribute, as `{ name => result }`.
157
+ def amount_fold_group(definitions, operations, rows, &fold)
158
+ width = operations.size + 1
159
+
160
+ definitions.each_with_index.to_h do |definition, index|
161
+ slices = rows.map { |row| row[index * width, width] }
162
+
163
+ [definition.name, amount_fold(definition, operations, slices, &fold)]
164
+ end
165
+ end
166
+
167
+ # One attribute's slices `[symbol, *aggregates]`, one per row: the rows
168
+ # without its amount are skipped, the rest must share one symbol, and
169
+ # each aggregate is combined across them before the fold sees it.
170
+ def amount_fold(definition, operations, slices)
171
+ present = slices.reject { |symbol, *| symbol.nil? }
172
+ symbols = present.map(&:first).uniq
173
+ if symbols.size > 1
174
+ raise ::Amount::TypeMismatch, "#{definition.name} has more than one symbol in scope: #{symbols.join(', ')}"
120
175
  end
121
176
 
122
- symbol, atomic, *rest = rows.first
123
- [definition.type.deserialize(atomic, symbol), *rest]
177
+ atomic, *rest = operations.each_with_index.map do |operation, index|
178
+ amount_combine(operation, present.map { |slice| slice[index + 1] })
179
+ end
180
+
181
+ yield(definition, definition.type.deserialize(atomic, symbols.first), *rest)
182
+ end
183
+
184
+ # Several rows' partial aggregates as one: sums and counts add up, and
185
+ # the minimum or maximum is that of the partials. Over no rows, a count
186
+ # is zero and everything else `nil`.
187
+ def amount_combine(operation, values)
188
+ values = values.compact
189
+ return values.sum if operation == :count
190
+ return if values.empty?
191
+
192
+ case operation
193
+ when :sum then values.sum
194
+ when :minimum then values.min
195
+ when :maximum then values.max
196
+ end
124
197
  end
125
198
  end
126
199
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class Amount
4
- VERSION = "0.3.0"
4
+ VERSION = "0.3.1"
5
5
  end
@@ -156,8 +156,128 @@ class AmountActiveRecordCalculationsTest < Minitest::Test
156
156
  assert_equal BigDecimal("150000000"), Holding.average(:fee_atomic)
157
157
  end
158
158
 
159
+ # Several attributes in one query
160
+
161
+ def test_sum_amount_of_several_attributes
162
+ assert_equal({ fee: Amount.new("0.3", :SOL), reserve: Amount.new("5", :USDC) },
163
+ Holding.sum_amount(:fee, :reserve))
164
+ end
165
+
166
+ def test_sum_amount_of_several_attributes_runs_one_query
167
+ assert_equal 1, queries_during { Holding.group(:amount_symbol).sum_amount(:amount, :fee, :reserve) }
168
+ end
169
+
170
+ def test_sum_amount_of_several_attributes_keys_by_name_given_as_strings
171
+ assert_equal %i[fee reserve], Holding.sum_amount("fee", "reserve").keys
172
+ end
173
+
174
+ def test_sum_amount_of_several_attributes_grouped
175
+ assert_equal(
176
+ {
177
+ nil => { amount: nil, fee: Amount.new(0, :SOL) },
178
+ "USD" => { amount: Amount.new("3", :USD), fee: Amount.new(0, :SOL) },
179
+ "USDC" => { amount: Amount.new("3.5", :USDC), fee: Amount.new("0.3", :SOL) }
180
+ },
181
+ Holding.group(:amount_symbol).sum_amount(:amount, :fee)
182
+ )
183
+ end
184
+
185
+ # Rows (USDC, USDC) and (NULL, USDC): amount sums only its own row, reserve
186
+ # adds both.
187
+ def test_sum_amount_of_several_multi_symbol_attributes_combines_rows
188
+ assert_equal({ amount: Amount.new("3.5", :USDC), reserve: Amount.new("3.75", :USDC) },
189
+ Holding.where(amount_symbol: ["USDC", nil]).sum_amount(:amount, :reserve))
190
+ end
191
+
192
+ def test_sum_amount_of_several_attributes_keeps_a_group_without_one_of_them
193
+ assert_equal({ amount: nil, reserve: Amount.new("1.25", :USDC) },
194
+ Holding.group(:amount_symbol).sum_amount(:amount, :reserve).fetch(nil))
195
+ end
196
+
197
+ def test_sum_amount_of_several_attributes_with_mixed_symbols_raises_type_mismatch
198
+ assert_raises(Amount::TypeMismatch) { Holding.sum_amount(:fee, :amount) }
199
+ end
200
+
201
+ def test_sum_amount_of_several_attributes_with_mixed_symbols_names_the_attribute
202
+ assert_match(/\Aamount has more than one symbol in scope/,
203
+ error_from(Amount::TypeMismatch) { Holding.sum_amount(:fee, :amount) }.message)
204
+ end
205
+
206
+ def test_sum_amount_of_several_attributes_over_no_rows
207
+ assert_equal({ fee: Amount.new(0, :SOL), amount: nil }, Holding.where(id: nil).sum_amount(:fee, :amount))
208
+ end
209
+
210
+ def test_sum_amount_of_several_attributes_on_none
211
+ assert_equal({ fee: Amount.new(0, :SOL), amount: nil }, Holding.none.sum_amount(:fee, :amount))
212
+ end
213
+
214
+ def test_sum_amount_of_several_attributes_grouped_on_none_is_empty
215
+ assert_empty Holding.none.group(:amount_symbol).sum_amount(:amount, :fee)
216
+ end
217
+
218
+ def test_sum_amount_of_several_attributes_grouped_by_two_columns_keys_by_array
219
+ assert_equal [["USDC", nil], %w[USDC USD], %w[USDC USDC]].to_set,
220
+ Holding.group(:reserve_symbol, :amount_symbol).sum_amount(:amount, :fee).keys.to_set
221
+ end
222
+
223
+ def test_sum_amount_with_a_name_given_twice_raises_argument_error
224
+ assert_raises(ArgumentError) { Holding.sum_amount(:fee, :fee) }
225
+ end
226
+
227
+ def test_sum_amount_without_names_raises_argument_error
228
+ assert_raises(ArgumentError) { Holding.sum_amount }
229
+ end
230
+
231
+ def test_sum_amount_of_an_unknown_name_raises_key_error
232
+ assert_raises(KeyError) { Holding.sum_amount(:fee, :nope) }
233
+ end
234
+
235
+ def test_minimum_amount_of_several_attributes
236
+ assert_equal({ fee: Amount.new("0.1", :SOL), reserve: Amount.new("1.25", :USDC) },
237
+ Holding.minimum_amount(:fee, :reserve))
238
+ end
239
+
240
+ def test_minimum_amount_of_several_multi_symbol_attributes_combines_rows
241
+ assert_equal({ amount: Amount.new("1.5", :USDC), reserve: Amount.new("1.25", :USDC) },
242
+ Holding.where(amount_symbol: ["USDC", nil]).minimum_amount(:amount, :reserve))
243
+ end
244
+
245
+ def test_maximum_amount_of_several_attributes_grouped
246
+ assert_equal({ amount: Amount.new("2", :USDC), fee: Amount.new("0.2", :SOL) },
247
+ Holding.group(:amount_symbol).maximum_amount(:amount, :fee).fetch("USDC"))
248
+ end
249
+
250
+ def test_average_amount_of_several_attributes
251
+ assert_equal({ fee: Amount.new("0.15", :SOL), reserve: Amount.new("1.25", :USDC) },
252
+ Holding.average_amount(:fee, :reserve))
253
+ end
254
+
255
+ def test_average_amount_of_several_multi_symbol_attributes_combines_rows
256
+ assert_equal({ amount: Amount.new("1.75", :USDC), reserve: Amount.new("1.25", :USDC) },
257
+ Holding.where(amount_symbol: ["USDC", nil]).average_amount(:amount, :reserve))
258
+ end
259
+
260
+ def test_average_amount_of_several_attributes_truncates_toward_zero
261
+ holdings_with_atomic_fees(1, 2)
262
+
263
+ assert_equal Amount.new(1, :SOL, from: :atomic), Holding.average_amount(:fee, :reserve).fetch(:fee)
264
+ end
265
+
266
+ def test_average_amount_of_several_attributes_is_nil_for_one_without_amounts
267
+ assert_equal({ amount: Amount.new("3", :USD), fee: nil },
268
+ Holding.group(:amount_symbol).average_amount(:amount, :fee).fetch("USD"))
269
+ end
270
+
159
271
  private
160
272
 
273
+ # How many SQL statements the block runs, schema queries aside.
274
+ def queries_during(&)
275
+ count = 0
276
+ counter = ->(*, payload) { count += 1 unless payload[:name] == "SCHEMA" }
277
+ ::ActiveSupport::Notifications.subscribed(counter, "sql.active_record", &)
278
+ count
279
+ end
280
+
161
281
  def holdings_with_atomic_fees(*atomics)
162
282
  Holding.delete_all
163
283
  atomics.each { |atomic| Holding.create!(fee: Amount.new(atomic, :SOL, from: :atomic)) }
@@ -95,6 +95,27 @@ class PostgreSQLIntegrationTest < Minitest::Test
95
95
  Holding.group(:amount_symbol).sum_amount(:amount))
96
96
  end
97
97
 
98
+ def test_postgresql_sum_amount_of_several_attributes_is_exact_past_64_bits
99
+ holdings_with_atomic_amounts(10**30, (10**30) + 1)
100
+
101
+ assert_equal({ amount: Amount.new((2 * (10**30)) + 1, :SOL, from: :atomic), fee: Amount.new(0, :SOL) },
102
+ Holding.sum_amount(:amount, :fee))
103
+ end
104
+
105
+ def test_postgresql_average_amount_of_several_attributes_is_exact_past_64_bits
106
+ holdings_with_atomic_amounts(10**30, (10**30) + 3)
107
+
108
+ assert_equal Amount.new((10**30) + 1, :SOL, from: :atomic),
109
+ Holding.average_amount(:amount, :reserve).fetch(:amount)
110
+ end
111
+
112
+ def test_postgresql_sum_amount_of_several_attributes_grouped
113
+ create_usdc_and_usd_holdings
114
+
115
+ assert_equal({ amount: Amount.new("1.5", :USDC), reserve: Amount.new("1.25", :USDC) },
116
+ Holding.group(:amount_symbol).sum_amount(:amount, :reserve).fetch("USDC"))
117
+ end
118
+
98
119
  private
99
120
 
100
121
  def holdings_with_atomic_amounts(*atomics)
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: amounts
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.0
4
+ version: 0.3.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Seb Scholl