1use super::float_sum::FloatSum;
4use super::{super::Plan, Aggregate, Completed, GroupValue, Query, Reducer};
5use crate::{
6 Decimal, Entity, EntitySchema, Error, FieldType, IndexValue, TypeBody, TypeSchema, U256, Value,
7 ValueSchema, codec::Encoder,
8};
9use ethnum::I256;
10use ic_storage::Memory;
11
12impl<E: Entity, M: Memory> Query<'_, E, M> {
13 pub fn sum<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
32 let (plan, reducer) = self.numeric_plan::<R>(None, Operation::Sum)?;
33
34 self.scalar_value(&plan, reducer)
35 }
36
37 pub fn group_sum<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
49 let (plan, reducer) = self.numeric_plan::<R>(Some(K::definition()), Operation::Sum)?;
50
51 self.group_values(&plan, reducer)
52 }
53
54 pub fn avg<R: Value>(self) -> Result<Aggregate<Option<R>>, Error> {
68 let (plan, reducer) = self.numeric_plan::<R>(None, Operation::Average)?;
69
70 self.scalar_value(&plan, reducer)
71 }
72
73 pub fn group_avg<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
82 let (plan, reducer) = self.numeric_plan::<R>(Some(K::definition()), Operation::Average)?;
83
84 self.group_values(&plan, reducer)
85 }
86
87 pub(super) fn numeric_plan<R: Value>(
89 &self,
90 group: Option<&TypeSchema>,
91 operation: Operation,
92 ) -> Result<(Plan<'static>, Reducer), Error> {
93 let mut plan = self.aggregate_plan(group, group.is_some())?;
94 let state = NumericAggregate::admit(E::SCHEMA, R::definition(), operation)?;
95 plan.selected |= 1 << state.position;
96
97 Ok((plan, Reducer::Numeric(state)))
98 }
99}
100
101#[derive(Clone, Copy)]
102#[repr(u8)]
103pub(super) enum Operation {
104 Sum = 1,
106 Average = 2,
107}
108
109#[derive(Clone)]
110pub(in crate::store::query) struct NumericAggregate {
111 pub(super) position: usize,
112 source_scale: u32,
113 output: ValueSchema,
114 total: Total,
115 count: u64,
116 pub(super) operation: Operation,
117}
118#[derive(Clone)]
119enum Total {
120 Float(Box<FloatSum>),
121 Signed(I256),
122 Unsigned(U256),
123}
124impl Total {
125 fn integer_zero(signed: bool) -> Self {
126 if signed {
127 Self::Signed(I256::ZERO)
128 } else {
129 Self::Unsigned(U256::ZERO)
130 }
131 }
132}
133
134impl NumericAggregate {
135 fn admit(
136 entity: &EntitySchema,
137 output: &TypeSchema,
138 operation: Operation,
139 ) -> Result<Self, Error> {
140 let TypeBody::Record([result]) = output.body else {
141 return Err(Error::InvalidQuery);
142 };
143 let position = entity
144 .field_position(result.name)
145 .ok_or(Error::InvalidQuery)?;
146 let source = &entity.fields[position];
147 if source.optional != result.optional {
148 return Err(Error::InvalidQuery);
149 }
150 let input = crate::key::operand_type(source.value);
151 if matches!(result.value, FieldType::Named(_)) {
153 super::admit_projection(entity, output)?;
154 }
155 let result_type = crate::key::operand_type(result.value);
156 let source_scale = match input {
157 FieldType::Decimal { scale } => scale,
158 _ => 0,
159 };
160 let total = match (operation, input, result_type) {
161 (Operation::Sum, FieldType::Float64, FieldType::Float64) => {
162 Total::Float(Box::default())
163 }
164 (
165 Operation::Sum,
166 FieldType::Decimal { scale: from },
167 FieldType::Decimal { scale: to },
168 ) if from == to => Total::Signed(I256::ZERO),
169 (
170 Operation::Average,
171 FieldType::Decimal { .. },
172 FieldType::Decimal { scale: 0..=28 },
173 ) => Total::Signed(I256::ZERO),
174 (Operation::Average, source, FieldType::Decimal { scale: 0..=28 }) => {
175 Total::integer_zero(integer(source).ok_or(Error::InvalidQuery)?.0)
176 }
177 (Operation::Average, _, _) => return Err(Error::InvalidQuery),
178 (Operation::Sum, source, result) => {
179 let (signed, bits) = integer(source).ok_or(Error::InvalidQuery)?;
180 let (result_signed, result_bits) = integer(result).ok_or(Error::InvalidQuery)?;
181 if signed != result_signed || bits > result_bits {
182 return Err(Error::InvalidQuery);
183 }
184 Total::integer_zero(signed)
185 }
186 };
187 Ok(Self {
188 position,
189 source_scale,
190 output: ValueSchema {
191 value: result.value,
192 optional: result.optional,
193 },
194 total,
195 count: 0,
196 operation,
197 })
198 }
199
200 pub(super) fn push(&mut self, values: &[IndexValue<'_>]) -> Result<(), Error> {
201 let value = values[self.position];
202 if value == IndexValue::Absent {
203 return Ok(());
204 }
205 match &mut self.total {
206 Total::Float(total) => {
207 let IndexValue::Float64(value) = value else {
208 return Err(Error::Corrupt);
209 };
210 total.add(value);
211 }
212 Total::Signed(total) => {
213 let value = match value {
214 IndexValue::Int8(n) => i128::from(n),
215 IndexValue::Int16(n) => i128::from(n),
216 IndexValue::Int32(n) => i128::from(n),
217 IndexValue::Int64(n) => i128::from(n),
218 IndexValue::Int128(n) => n,
219 IndexValue::Decimal(n) => n
220 .coefficient_at_scale(self.source_scale)
221 .ok_or(Error::Corrupt)?,
222 _ => return Err(Error::Corrupt),
223 };
224 *total = total
227 .checked_add(I256::from(value))
228 .ok_or(Error::ArithmeticOverflow)?;
229 }
230 Total::Unsigned(total) => {
231 let value = match value {
232 IndexValue::Nat8(n) => U256::from(n),
233 IndexValue::Nat16(n) => U256::from(n),
234 IndexValue::Nat32(n) => U256::from(n),
235 IndexValue::Nat64(n) => U256::from(n),
236 IndexValue::Nat128(n) => U256::from(n),
237 IndexValue::U256(n) => n,
238 _ => return Err(Error::Corrupt),
239 };
240 *total = total.checked_add(value).ok_or(Error::ArithmeticOverflow)?;
241 }
242 }
243 self.count = self.count.checked_add(1).ok_or(Error::ArithmeticOverflow)?;
244
245 Ok(())
246 }
247
248 pub(super) fn with_checkpoint<T>(&self, write: impl FnOnce(u64, &[u8]) -> T) -> T {
251 match &self.total {
252 Total::Signed(n) => write(self.count, &n.to_be_bytes()),
253 Total::Unsigned(n) => write(self.count, &n.to_be_bytes()),
254 Total::Float(sum) => write(self.count, sum.checkpoint().as_flattened()),
255 }
256 }
257
258 pub(super) fn restore(&mut self, count: u64, bytes: &[u8]) -> Result<(), Error> {
259 match &mut self.total {
260 Total::Signed(n) => {
261 *n = I256::from_be_bytes(bytes.try_into().map_err(|_| Error::Corrupt)?)
262 }
263 Total::Unsigned(n) => {
264 *n = U256::from_be_bytes(bytes.try_into().map_err(|_| Error::Corrupt)?)
265 }
266 Total::Float(sum) => sum.restore(count, bytes)?,
267 }
268 self.count = count;
269 Ok(())
270 }
271
272 pub(super) fn total_bytes(&self) -> usize {
273 if matches!(self.total, Total::Float(_)) {
274 FloatSum::BYTES
275 } else {
276 32
277 }
278 }
279
280 pub(super) fn retained_bytes(&self) -> usize {
281 self.total_bytes()
282 + if matches!(self.operation, Operation::Average) {
283 8
284 } else {
285 0
286 }
287 }
288
289 pub(super) fn output(&self) -> ValueSchema {
290 self.output
291 }
292
293 pub(super) fn finish(mut self) -> Result<Completed, Error> {
294 if self.count == 0 {
295 return Ok(Completed::Value(None));
296 }
297 let result_type = crate::key::operand_type(self.output.value);
298 if matches!(self.operation, Operation::Average) {
299 let FieldType::Decimal { scale } = result_type else {
300 return Err(Error::Corrupt);
301 };
302 let numerator = match self.total {
303 Total::Float(_) => return Err(Error::Corrupt),
304 Total::Signed(n) => n,
305 Total::Unsigned(n) => n.try_into().map_err(|_| Error::ArithmeticOverflow)?,
309 };
310 self.total = Total::Signed(rounded_average(
311 numerator,
312 self.count,
313 self.source_scale,
314 scale,
315 )?);
316 }
317 let mut output = Encoder::new();
318 let mut key = Vec::new();
319 if self.output.optional {
320 output.boolean(true)?;
321 }
322 macro_rules! encode {
325 ($method:ident, $variant:ident, $value:expr) => {{
326 let value = $value.try_into().map_err(|_| Error::ArithmeticOverflow)?;
327 output.$method(value)?;
328 IndexValue::$variant(value).append_component(self.output.optional, &mut key);
329 }};
330 }
331 match (self.total, result_type) {
332 (Total::Float(sum), FieldType::Float64) => {
333 let value = sum.finish()?;
334 output.float64(value)?;
335 IndexValue::Float64(value).append_component(self.output.optional, &mut key);
336 }
337 (Total::Signed(n), FieldType::Int8) => encode!(int8, Int8, n),
338 (Total::Signed(n), FieldType::Int16) => encode!(int16, Int16, n),
339 (Total::Signed(n), FieldType::Int32) => encode!(int32, Int32, n),
340 (Total::Signed(n), FieldType::Int64) => encode!(int64, Int64, n),
341 (Total::Signed(n), FieldType::Int128) => encode!(int128, Int128, n),
342 (Total::Signed(n), FieldType::Decimal { scale }) => {
343 let coefficient = n.try_into().map_err(|_| Error::ArithmeticOverflow)?;
344 let value = Decimal::try_new(coefficient, scale).ok_or(Error::Corrupt)?;
345 output.decimal(value, scale)?;
346 IndexValue::Decimal(value).append_component(self.output.optional, &mut key);
347 }
348 (Total::Unsigned(n), FieldType::Nat8) => encode!(nat8, Nat8, n),
349 (Total::Unsigned(n), FieldType::Nat16) => encode!(nat16, Nat16, n),
350 (Total::Unsigned(n), FieldType::Nat32) => encode!(nat32, Nat32, n),
351 (Total::Unsigned(n), FieldType::Nat64) => encode!(nat64, Nat64, n),
352 (Total::Unsigned(n), FieldType::Nat128) => encode!(nat128, Nat128, n),
353 (Total::Unsigned(n), FieldType::U256) => {
354 output.u256(n)?;
355 IndexValue::U256(n).append_component(self.output.optional, &mut key);
356 }
357 _ => return Err(Error::Corrupt),
358 }
359
360 Ok(Completed::Value(Some((key, output.finish()))))
361 }
362}
363
364fn rounded_average(
365 total: I256,
366 count: u64,
367 source_scale: u32,
368 result_scale: u32,
369) -> Result<I256, Error> {
370 let factor = I256::from(10_i128.pow(source_scale.abs_diff(result_scale)));
375 let (numerator, denominator) = if result_scale >= source_scale {
376 (
377 total.checked_mul(factor).ok_or(Error::ArithmeticOverflow)?,
378 I256::from(count),
379 )
380 } else {
381 (total, I256::from(count) * factor)
382 };
383 let quotient = numerator / denominator;
384 let twice_remainder = (numerator % denominator).abs() * 2;
385 let round = twice_remainder > denominator
386 || (twice_remainder == denominator && quotient % 2 != I256::ZERO);
387
388 Ok(if round {
389 quotient
390 + if numerator < I256::ZERO {
391 I256::MINUS_ONE
392 } else {
393 I256::ONE
394 }
395 } else {
396 quotient
397 })
398}
399
400fn integer(value: FieldType) -> Option<(bool, u16)> {
401 Some(match value {
402 FieldType::Nat8 => (false, 8),
403 FieldType::Int8 => (true, 8),
404 FieldType::Nat16 => (false, 16),
405 FieldType::Int16 => (true, 16),
406 FieldType::Nat32 => (false, 32),
407 FieldType::Int32 => (true, 32),
408 FieldType::Nat64 => (false, 64),
409 FieldType::Int64 => (true, 64),
410 FieldType::Nat128 => (false, 128),
411 FieldType::Int128 => (true, 128),
412 FieldType::U256 => (false, 256),
413 _ => return None,
414 })
415}