1use super::float_sum::{Binary32Sum, Binary64Sum};
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> {
67 let (plan, reducer) = self.numeric_plan::<R>(None, Operation::Average)?;
68
69 self.scalar_value(&plan, reducer)
70 }
71
72 pub fn group_avg<K: Value, R: Value>(self) -> Result<Aggregate<Vec<GroupValue<K, R>>>, Error> {
81 let (plan, reducer) = self.numeric_plan::<R>(Some(K::definition()), Operation::Average)?;
82
83 self.group_values(&plan, reducer)
84 }
85
86 pub(super) fn numeric_plan<R: Value>(
88 &self,
89 group: Option<&TypeSchema>,
90 operation: Operation,
91 ) -> Result<(Plan<'static>, Reducer), Error> {
92 let mut plan = self.aggregate_plan(group, group.is_some())?;
93 let state = NumericAggregate::admit(E::SCHEMA, R::definition(), operation)?;
94 plan.selected |= 1 << state.position;
95
96 Ok((plan, Reducer::Numeric(state)))
97 }
98}
99
100#[derive(Clone, Copy)]
101#[repr(u8)]
102pub(super) enum Operation {
103 Sum = 1,
105 Average = 2,
106}
107
108#[derive(Clone)]
109pub(in crate::store::query) struct NumericAggregate {
110 pub(super) position: usize,
111 source_scale: u32,
112 output: ValueSchema,
113 total: Total,
114 count: u64,
115 pub(super) operation: Operation,
116}
117#[derive(Clone)]
118enum Total {
119 Float32(Box<Binary32Sum>),
120 Float64(Box<Binary64Sum>),
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 (_, FieldType::Float32, FieldType::Float32) => Total::Float32(Box::default()),
162 (_, FieldType::Float64, FieldType::Float64) => Total::Float64(Box::default()),
163 (
164 Operation::Sum,
165 FieldType::Decimal { scale: from },
166 FieldType::Decimal { scale: to },
167 ) if from == to => Total::Signed(I256::ZERO),
168 (
169 Operation::Average,
170 FieldType::Decimal { .. },
171 FieldType::Decimal { scale: 0..=28 },
172 ) => Total::Signed(I256::ZERO),
173 (Operation::Average, source, FieldType::Decimal { scale: 0..=28 }) => {
174 Total::integer_zero(integer(source).ok_or(Error::InvalidQuery)?.0)
175 }
176 (Operation::Average, _, _) => return Err(Error::InvalidQuery),
177 (Operation::Sum, source, result) => {
178 let (signed, bits) = integer(source).ok_or(Error::InvalidQuery)?;
179 let (result_signed, result_bits) = integer(result).ok_or(Error::InvalidQuery)?;
180 if signed != result_signed || bits > result_bits {
181 return Err(Error::InvalidQuery);
182 }
183 Total::integer_zero(signed)
184 }
185 };
186 Ok(Self {
187 position,
188 source_scale,
189 output: ValueSchema {
190 value: result.value,
191 optional: result.optional,
192 },
193 total,
194 count: 0,
195 operation,
196 })
197 }
198
199 pub(super) fn push(&mut self, values: &[IndexValue<'_>]) -> Result<(), Error> {
200 let value = values[self.position];
201 if value == IndexValue::Absent {
202 return Ok(());
203 }
204 match &mut self.total {
205 Total::Float32(total) => {
206 let IndexValue::Float32(value) = value else {
207 return Err(Error::Corrupt);
208 };
209 total.add(value);
210 }
211 Total::Float64(total) => {
212 let IndexValue::Float64(value) = value else {
213 return Err(Error::Corrupt);
214 };
215 total.add(value);
216 }
217 Total::Signed(total) => {
218 let value = match value {
219 IndexValue::Int8(n) => i128::from(n),
220 IndexValue::Int16(n) => i128::from(n),
221 IndexValue::Int32(n) => i128::from(n),
222 IndexValue::Int64(n) => i128::from(n),
223 IndexValue::Int128(n) => n,
224 IndexValue::Decimal(n) => n
225 .coefficient_at_scale(self.source_scale)
226 .ok_or(Error::Corrupt)?,
227 _ => return Err(Error::Corrupt),
228 };
229 *total = total
232 .checked_add(I256::from(value))
233 .ok_or(Error::ArithmeticOverflow)?;
234 }
235 Total::Unsigned(total) => {
236 let value = match value {
237 IndexValue::Nat8(n) => U256::from(n),
238 IndexValue::Nat16(n) => U256::from(n),
239 IndexValue::Nat32(n) => U256::from(n),
240 IndexValue::Nat64(n) => U256::from(n),
241 IndexValue::Nat128(n) => U256::from(n),
242 IndexValue::U256(n) => n,
243 _ => return Err(Error::Corrupt),
244 };
245 *total = total.checked_add(value).ok_or(Error::ArithmeticOverflow)?;
246 }
247 }
248 self.count = self.count.checked_add(1).ok_or(Error::ArithmeticOverflow)?;
249
250 Ok(())
251 }
252
253 pub(super) fn with_checkpoint<T>(&self, write: impl FnOnce(u64, &[u8]) -> T) -> T {
256 match &self.total {
257 Total::Signed(n) => write(self.count, &n.to_be_bytes()),
258 Total::Unsigned(n) => write(self.count, &n.to_be_bytes()),
259 Total::Float32(sum) => write(self.count, sum.checkpoint().as_flattened()),
260 Total::Float64(sum) => write(self.count, sum.checkpoint().as_flattened()),
261 }
262 }
263
264 pub(super) fn restore(&mut self, count: u64, bytes: &[u8]) -> Result<(), Error> {
265 match &mut self.total {
266 Total::Signed(n) => {
267 *n = I256::from_be_bytes(bytes.try_into().map_err(|_| Error::Corrupt)?)
268 }
269 Total::Unsigned(n) => {
270 *n = U256::from_be_bytes(bytes.try_into().map_err(|_| Error::Corrupt)?)
271 }
272 Total::Float32(sum) => sum.restore(count, bytes)?,
273 Total::Float64(sum) => sum.restore(count, bytes)?,
274 }
275 self.count = count;
276 Ok(())
277 }
278
279 pub(super) fn total_bytes(&self) -> usize {
280 match self.total {
281 Total::Float32(_) => Binary32Sum::BYTES,
282 Total::Float64(_) => Binary64Sum::BYTES,
283 Total::Signed(_) | Total::Unsigned(_) => 32,
284 }
285 }
286
287 pub(super) fn retained_bytes(&self) -> usize {
288 self.total_bytes()
289 + if matches!(self.operation, Operation::Average) {
290 8
291 } else {
292 0
293 }
294 }
295
296 pub(super) fn output(&self) -> ValueSchema {
297 self.output
298 }
299
300 pub(super) fn finish(mut self) -> Result<Completed, Error> {
301 if self.count == 0 {
302 return Ok(Completed::Value(None));
303 }
304 let result_type = crate::key::operand_type(self.output.value);
305 if let (Operation::Average, FieldType::Decimal { scale }) = (self.operation, result_type) {
306 let numerator = match self.total {
307 Total::Float32(_) | Total::Float64(_) => return Err(Error::Corrupt),
308 Total::Signed(n) => n,
309 Total::Unsigned(n) => n.try_into().map_err(|_| Error::ArithmeticOverflow)?,
313 };
314 self.total = Total::Signed(rounded_average(
315 numerator,
316 self.count,
317 self.source_scale,
318 scale,
319 )?);
320 }
321 let mut output = Encoder::new();
322 let mut key = Vec::new();
323 if self.output.optional {
324 output.boolean(true)?;
325 }
326 macro_rules! encode {
329 ($method:ident, $variant:ident, $value:expr) => {{
330 let value = $value.try_into().map_err(|_| Error::ArithmeticOverflow)?;
331 output.$method(value)?;
332 IndexValue::$variant(value).append_component(self.output.optional, &mut key);
333 }};
334 }
335 let divisor = match self.operation {
336 Operation::Sum => 1,
337 Operation::Average => self.count,
338 };
339 match (self.total, result_type) {
340 (Total::Float32(sum), FieldType::Float32) => {
341 let value = sum.finish(divisor)?;
342 output.float32(value)?;
343 IndexValue::Float32(value).append_component(self.output.optional, &mut key);
344 }
345 (Total::Float64(sum), FieldType::Float64) => {
346 let value = sum.finish(divisor)?;
347 output.float64(value)?;
348 IndexValue::Float64(value).append_component(self.output.optional, &mut key);
349 }
350 (Total::Signed(n), FieldType::Int8) => encode!(int8, Int8, n),
351 (Total::Signed(n), FieldType::Int16) => encode!(int16, Int16, n),
352 (Total::Signed(n), FieldType::Int32) => encode!(int32, Int32, n),
353 (Total::Signed(n), FieldType::Int64) => encode!(int64, Int64, n),
354 (Total::Signed(n), FieldType::Int128) => encode!(int128, Int128, n),
355 (Total::Signed(n), FieldType::Decimal { scale }) => {
356 let coefficient = n.try_into().map_err(|_| Error::ArithmeticOverflow)?;
357 let value = Decimal::try_new(coefficient, scale).ok_or(Error::Corrupt)?;
358 output.decimal(value, scale)?;
359 IndexValue::Decimal(value).append_component(self.output.optional, &mut key);
360 }
361 (Total::Unsigned(n), FieldType::Nat8) => encode!(nat8, Nat8, n),
362 (Total::Unsigned(n), FieldType::Nat16) => encode!(nat16, Nat16, n),
363 (Total::Unsigned(n), FieldType::Nat32) => encode!(nat32, Nat32, n),
364 (Total::Unsigned(n), FieldType::Nat64) => encode!(nat64, Nat64, n),
365 (Total::Unsigned(n), FieldType::Nat128) => encode!(nat128, Nat128, n),
366 (Total::Unsigned(n), FieldType::U256) => {
367 output.u256(n)?;
368 IndexValue::U256(n).append_component(self.output.optional, &mut key);
369 }
370 _ => return Err(Error::Corrupt),
371 }
372
373 Ok(Completed::Value(Some((key, output.finish()))))
374 }
375}
376
377fn rounded_average(
378 total: I256,
379 count: u64,
380 source_scale: u32,
381 result_scale: u32,
382) -> Result<I256, Error> {
383 let factor = I256::from(10_i128.pow(source_scale.abs_diff(result_scale)));
388 let (numerator, denominator) = if result_scale >= source_scale {
389 (
390 total.checked_mul(factor).ok_or(Error::ArithmeticOverflow)?,
391 I256::from(count),
392 )
393 } else {
394 (total, I256::from(count) * factor)
395 };
396 let quotient = numerator / denominator;
397 let twice_remainder = (numerator % denominator).abs() * 2;
398 let round = twice_remainder > denominator
399 || (twice_remainder == denominator && quotient % 2 != I256::ZERO);
400
401 Ok(if round {
402 quotient
403 + if numerator < I256::ZERO {
404 I256::MINUS_ONE
405 } else {
406 I256::ONE
407 }
408 } else {
409 quotient
410 })
411}
412
413fn integer(value: FieldType) -> Option<(bool, u16)> {
414 Some(match value {
415 FieldType::Nat8 => (false, 8),
416 FieldType::Int8 => (true, 8),
417 FieldType::Nat16 => (false, 16),
418 FieldType::Int16 => (true, 16),
419 FieldType::Nat32 => (false, 32),
420 FieldType::Int32 => (true, 32),
421 FieldType::Nat64 => (false, 64),
422 FieldType::Int64 => (true, 64),
423 FieldType::Nat128 => (false, 128),
424 FieldType::Int128 => (true, 128),
425 FieldType::U256 => (false, 256),
426 _ => return None,
427 })
428}