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