PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
numeric.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * numeric.c
4  * An exact numeric data type for the Postgres database system
5  *
6  * Original coding 1998, Jan Wieck. Heavily revised 2003, Tom Lane.
7  *
8  * Many of the algorithmic ideas are borrowed from David M. Smith's "FM"
9  * multiple-precision math library, most recently published as Algorithm
10  * 786: Multiple-Precision Complex Arithmetic and Functions, ACM
11  * Transactions on Mathematical Software, Vol. 24, No. 4, December 1998,
12  * pages 359-367.
13  *
14  * Copyright (c) 1998-2017, PostgreSQL Global Development Group
15  *
16  * IDENTIFICATION
17  * src/backend/utils/adt/numeric.c
18  *
19  *-------------------------------------------------------------------------
20  */
21 
22 #include "postgres.h"
23 
24 #include <ctype.h>
25 #include <float.h>
26 #include <limits.h>
27 #include <math.h>
28 
29 #include "access/hash.h"
30 #include "catalog/pg_type.h"
31 #include "funcapi.h"
32 #include "lib/hyperloglog.h"
33 #include "libpq/pqformat.h"
34 #include "miscadmin.h"
35 #include "nodes/nodeFuncs.h"
36 #include "utils/array.h"
37 #include "utils/builtins.h"
38 #include "utils/guc.h"
39 #include "utils/int8.h"
40 #include "utils/numeric.h"
41 #include "utils/sortsupport.h"
42 
43 /* ----------
44  * Uncomment the following to enable compilation of dump_numeric()
45  * and dump_var() and to get a dump of any result produced by make_result().
46  * ----------
47 #define NUMERIC_DEBUG
48  */
49 
50 
51 /* ----------
52  * Local data types
53  *
54  * Numeric values are represented in a base-NBASE floating point format.
55  * Each "digit" ranges from 0 to NBASE-1. The type NumericDigit is signed
56  * and wide enough to store a digit. We assume that NBASE*NBASE can fit in
57  * an int. Although the purely calculational routines could handle any even
58  * NBASE that's less than sqrt(INT_MAX), in practice we are only interested
59  * in NBASE a power of ten, so that I/O conversions and decimal rounding
60  * are easy. Also, it's actually more efficient if NBASE is rather less than
61  * sqrt(INT_MAX), so that there is "headroom" for mul_var and div_var_fast to
62  * postpone processing carries.
63  *
64  * Values of NBASE other than 10000 are considered of historical interest only
65  * and are no longer supported in any sense; no mechanism exists for the client
66  * to discover the base, so every client supporting binary mode expects the
67  * base-10000 format. If you plan to change this, also note the numeric
68  * abbreviation code, which assumes NBASE=10000.
69  * ----------
70  */
71 
72 #if 0
73 #define NBASE 10
74 #define HALF_NBASE 5
75 #define DEC_DIGITS 1 /* decimal digits per NBASE digit */
76 #define MUL_GUARD_DIGITS 4 /* these are measured in NBASE digits */
77 #define DIV_GUARD_DIGITS 8
78 
79 typedef signed char NumericDigit;
80 #endif
81 
82 #if 0
83 #define NBASE 100
84 #define HALF_NBASE 50
85 #define DEC_DIGITS 2 /* decimal digits per NBASE digit */
86 #define MUL_GUARD_DIGITS 3 /* these are measured in NBASE digits */
87 #define DIV_GUARD_DIGITS 6
88 
89 typedef signed char NumericDigit;
90 #endif
91 
92 #if 1
93 #define NBASE 10000
94 #define HALF_NBASE 5000
95 #define DEC_DIGITS 4 /* decimal digits per NBASE digit */
96 #define MUL_GUARD_DIGITS 2 /* these are measured in NBASE digits */
97 #define DIV_GUARD_DIGITS 4
98 
100 #endif
101 
102 /*
103  * The Numeric type as stored on disk.
104  *
105  * If the high bits of the first word of a NumericChoice (n_header, or
106  * n_short.n_header, or n_long.n_sign_dscale) are NUMERIC_SHORT, then the
107  * numeric follows the NumericShort format; if they are NUMERIC_POS or
108  * NUMERIC_NEG, it follows the NumericLong format. If they are NUMERIC_NAN,
109  * it is a NaN. We currently always store a NaN using just two bytes (i.e.
110  * only n_header), but previous releases used only the NumericLong format,
111  * so we might find 4-byte NaNs on disk if a database has been migrated using
112  * pg_upgrade. In either case, when the high bits indicate a NaN, the
113  * remaining bits are never examined. Currently, we always initialize these
114  * to zero, but it might be possible to use them for some other purpose in
115  * the future.
116  *
117  * In the NumericShort format, the remaining 14 bits of the header word
118  * (n_short.n_header) are allocated as follows: 1 for sign (positive or
119  * negative), 6 for dynamic scale, and 7 for weight. In practice, most
120  * commonly-encountered values can be represented this way.
121  *
122  * In the NumericLong format, the remaining 14 bits of the header word
123  * (n_long.n_sign_dscale) represent the display scale; and the weight is
124  * stored separately in n_weight.
125  *
126  * NOTE: by convention, values in the packed form have been stripped of
127  * all leading and trailing zero digits (where a "digit" is of base NBASE).
128  * In particular, if the value is zero, there will be no digits at all!
129  * The weight is arbitrary in that case, but we normally set it to zero.
130  */
131 
133 {
134  uint16 n_header; /* Sign + display scale + weight */
135  NumericDigit n_data[FLEXIBLE_ARRAY_MEMBER]; /* Digits */
136 };
137 
139 {
140  uint16 n_sign_dscale; /* Sign + display scale */
141  int16 n_weight; /* Weight of 1st digit */
142  NumericDigit n_data[FLEXIBLE_ARRAY_MEMBER]; /* Digits */
143 };
144 
146 {
147  uint16 n_header; /* Header word */
148  struct NumericLong n_long; /* Long form (4-byte header) */
149  struct NumericShort n_short; /* Short form (2-byte header) */
150 };
151 
153 {
154  int32 vl_len_; /* varlena header (do not touch directly!) */
155  union NumericChoice choice; /* choice of format */
156 };
157 
158 
159 /*
160  * Interpretation of high bits.
161  */
162 
163 #define NUMERIC_SIGN_MASK 0xC000
164 #define NUMERIC_POS 0x0000
165 #define NUMERIC_NEG 0x4000
166 #define NUMERIC_SHORT 0x8000
167 #define NUMERIC_NAN 0xC000
168 
169 #define NUMERIC_FLAGBITS(n) ((n)->choice.n_header & NUMERIC_SIGN_MASK)
170 #define NUMERIC_IS_NAN(n) (NUMERIC_FLAGBITS(n) == NUMERIC_NAN)
171 #define NUMERIC_IS_SHORT(n) (NUMERIC_FLAGBITS(n) == NUMERIC_SHORT)
172 
173 #define NUMERIC_HDRSZ (VARHDRSZ + sizeof(uint16) + sizeof(int16))
174 #define NUMERIC_HDRSZ_SHORT (VARHDRSZ + sizeof(uint16))
175 
176 /*
177  * If the flag bits are NUMERIC_SHORT or NUMERIC_NAN, we want the short header;
178  * otherwise, we want the long one. Instead of testing against each value, we
179  * can just look at the high bit, for a slight efficiency gain.
180  */
181 #define NUMERIC_HEADER_IS_SHORT(n) (((n)->choice.n_header & 0x8000) != 0)
182 #define NUMERIC_HEADER_SIZE(n) \
183  (VARHDRSZ + sizeof(uint16) + \
184  (NUMERIC_HEADER_IS_SHORT(n) ? 0 : sizeof(int16)))
185 
186 /*
187  * Short format definitions.
188  */
189 
190 #define NUMERIC_SHORT_SIGN_MASK 0x2000
191 #define NUMERIC_SHORT_DSCALE_MASK 0x1F80
192 #define NUMERIC_SHORT_DSCALE_SHIFT 7
193 #define NUMERIC_SHORT_DSCALE_MAX \
194  (NUMERIC_SHORT_DSCALE_MASK >> NUMERIC_SHORT_DSCALE_SHIFT)
195 #define NUMERIC_SHORT_WEIGHT_SIGN_MASK 0x0040
196 #define NUMERIC_SHORT_WEIGHT_MASK 0x003F
197 #define NUMERIC_SHORT_WEIGHT_MAX NUMERIC_SHORT_WEIGHT_MASK
198 #define NUMERIC_SHORT_WEIGHT_MIN (-(NUMERIC_SHORT_WEIGHT_MASK+1))
199 
200 /*
201  * Extract sign, display scale, weight.
202  */
203 
204 #define NUMERIC_DSCALE_MASK 0x3FFF
205 
206 #define NUMERIC_SIGN(n) \
207  (NUMERIC_IS_SHORT(n) ? \
208  (((n)->choice.n_short.n_header & NUMERIC_SHORT_SIGN_MASK) ? \
209  NUMERIC_NEG : NUMERIC_POS) : NUMERIC_FLAGBITS(n))
210 #define NUMERIC_DSCALE(n) (NUMERIC_HEADER_IS_SHORT((n)) ? \
211  ((n)->choice.n_short.n_header & NUMERIC_SHORT_DSCALE_MASK) \
212  >> NUMERIC_SHORT_DSCALE_SHIFT \
213  : ((n)->choice.n_long.n_sign_dscale & NUMERIC_DSCALE_MASK))
214 #define NUMERIC_WEIGHT(n) (NUMERIC_HEADER_IS_SHORT((n)) ? \
215  (((n)->choice.n_short.n_header & NUMERIC_SHORT_WEIGHT_SIGN_MASK ? \
216  ~NUMERIC_SHORT_WEIGHT_MASK : 0) \
217  | ((n)->choice.n_short.n_header & NUMERIC_SHORT_WEIGHT_MASK)) \
218  : ((n)->choice.n_long.n_weight))
219 
220 /* ----------
221  * NumericVar is the format we use for arithmetic. The digit-array part
222  * is the same as the NumericData storage format, but the header is more
223  * complex.
224  *
225  * The value represented by a NumericVar is determined by the sign, weight,
226  * ndigits, and digits[] array.
227  *
228  * Note: the first digit of a NumericVar's value is assumed to be multiplied
229  * by NBASE ** weight. Another way to say it is that there are weight+1
230  * digits before the decimal point. It is possible to have weight < 0.
231  *
232  * buf points at the physical start of the palloc'd digit buffer for the
233  * NumericVar. digits points at the first digit in actual use (the one
234  * with the specified weight). We normally leave an unused digit or two
235  * (preset to zeroes) between buf and digits, so that there is room to store
236  * a carry out of the top digit without reallocating space. We just need to
237  * decrement digits (and increment weight) to make room for the carry digit.
238  * (There is no such extra space in a numeric value stored in the database,
239  * only in a NumericVar in memory.)
240  *
241  * If buf is NULL then the digit buffer isn't actually palloc'd and should
242  * not be freed --- see the constants below for an example.
243  *
244  * dscale, or display scale, is the nominal precision expressed as number
245  * of digits after the decimal point (it must always be >= 0 at present).
246  * dscale may be more than the number of physically stored fractional digits,
247  * implying that we have suppressed storage of significant trailing zeroes.
248  * It should never be less than the number of stored digits, since that would
249  * imply hiding digits that are present. NOTE that dscale is always expressed
250  * in *decimal* digits, and so it may correspond to a fractional number of
251  * base-NBASE digits --- divide by DEC_DIGITS to convert to NBASE digits.
252  *
253  * rscale, or result scale, is the target precision for a computation.
254  * Like dscale it is expressed as number of *decimal* digits after the decimal
255  * point, and is always >= 0 at present.
256  * Note that rscale is not stored in variables --- it's figured on-the-fly
257  * from the dscales of the inputs.
258  *
259  * While we consistently use "weight" to refer to the base-NBASE weight of
260  * a numeric value, it is convenient in some scale-related calculations to
261  * make use of the base-10 weight (ie, the approximate log10 of the value).
262  * To avoid confusion, such a decimal-units weight is called a "dweight".
263  *
264  * NB: All the variable-level functions are written in a style that makes it
265  * possible to give one and the same variable as argument and destination.
266  * This is feasible because the digit buffer is separate from the variable.
267  * ----------
268  */
269 typedef struct NumericVar
270 {
271  int ndigits; /* # of digits in digits[] - can be 0! */
272  int weight; /* weight of first digit */
273  int sign; /* NUMERIC_POS, NUMERIC_NEG, or NUMERIC_NAN */
274  int dscale; /* display scale */
275  NumericDigit *buf; /* start of palloc'd space for digits[] */
276  NumericDigit *digits; /* base-NBASE digits */
277 } NumericVar;
278 
279 
280 /* ----------
281  * Data for generate_series
282  * ----------
283  */
284 typedef struct
285 {
290 
291 
292 /* ----------
293  * Sort support.
294  * ----------
295  */
296 typedef struct
297 {
298  void *buf; /* buffer for short varlenas */
299  int64 input_count; /* number of non-null values seen */
300  bool estimating; /* true if estimating cardinality */
301 
302  hyperLogLogState abbr_card; /* cardinality estimator */
304 
305 
306 /* ----------
307  * Fast sum accumulator.
308  *
309  * NumericSumAccum is used to implement SUM(), and other standard aggregates
310  * that track the sum of input values. It uses 32-bit integers to store the
311  * digits, instead of the normal 16-bit integers (with NBASE=10000). This
312  * way, we can safely accumulate up to NBASE - 1 values without propagating
313  * carry, before risking overflow of any of the digits. 'num_uncarried'
314  * tracks how many values have been accumulated without propagating carry.
315  *
316  * Positive and negative values are accumulated separately, in 'pos_digits'
317  * and 'neg_digits'. This is simpler and faster than deciding whether to add
318  * or subtract from the current value, for each new value (see sub_var() for
319  * the logic we avoid by doing this). Both buffers are of same size, and
320  * have the same weight and scale. In accum_sum_final(), the positive and
321  * negative sums are added together to produce the final result.
322  *
323  * When a new value has a larger ndigits or weight than the accumulator
324  * currently does, the accumulator is enlarged to accommodate the new value.
325  * We normally have one zero digit reserved for carry propagation, and that
326  * is indicated by the 'have_carry_space' flag. When accum_sum_carry() uses
327  * up the reserved digit, it clears the 'have_carry_space' flag. The next
328  * call to accum_sum_add() will enlarge the buffer, to make room for the
329  * extra digit, and set the flag again.
330  *
331  * To initialize a new accumulator, simply reset all fields to zeros.
332  *
333  * The accumulator does not handle NaNs.
334  * ----------
335  */
336 typedef struct NumericSumAccum
337 {
338  int ndigits;
339  int weight;
340  int dscale;
346 
347 
348 /*
349  * We define our own macros for packing and unpacking abbreviated-key
350  * representations for numeric values in order to avoid depending on
351  * USE_FLOAT8_BYVAL. The type of abbreviation we use is based only on
352  * the size of a datum, not the argument-passing convention for float8.
353  */
354 #define NUMERIC_ABBREV_BITS (SIZEOF_DATUM * BITS_PER_BYTE)
355 #if SIZEOF_DATUM == 8
356 #define NumericAbbrevGetDatum(X) ((Datum) SET_8_BYTES(X))
357 #define DatumGetNumericAbbrev(X) ((int64) GET_8_BYTES(X))
358 #define NUMERIC_ABBREV_NAN NumericAbbrevGetDatum(PG_INT64_MIN)
359 #else
360 #define NumericAbbrevGetDatum(X) ((Datum) SET_4_BYTES(X))
361 #define DatumGetNumericAbbrev(X) ((int32) GET_4_BYTES(X))
362 #define NUMERIC_ABBREV_NAN NumericAbbrevGetDatum(PG_INT32_MIN)
363 #endif
364 
365 
366 /* ----------
367  * Some preinitialized constants
368  * ----------
369  */
372 {0, 0, NUMERIC_POS, 0, NULL, const_zero_data};
373 
374 static NumericDigit const_one_data[1] = {1};
376 {1, 0, NUMERIC_POS, 0, NULL, const_one_data};
377 
378 static NumericDigit const_two_data[1] = {2};
380 {1, 0, NUMERIC_POS, 0, NULL, const_two_data};
381 
382 #if DEC_DIGITS == 4 || DEC_DIGITS == 2
383 static NumericDigit const_ten_data[1] = {10};
385 {1, 0, NUMERIC_POS, 0, NULL, const_ten_data};
386 #elif DEC_DIGITS == 1
387 static NumericDigit const_ten_data[1] = {1};
388 static NumericVar const_ten =
389 {1, 1, NUMERIC_POS, 0, NULL, const_ten_data};
390 #endif
391 
392 #if DEC_DIGITS == 4
394 #elif DEC_DIGITS == 2
396 #elif DEC_DIGITS == 1
398 #endif
401 
402 #if DEC_DIGITS == 4
404 #elif DEC_DIGITS == 2
406 #elif DEC_DIGITS == 1
408 #endif
411 
412 #if DEC_DIGITS == 4
414 #elif DEC_DIGITS == 2
415 static NumericDigit const_one_point_one_data[2] = {1, 10};
416 #elif DEC_DIGITS == 1
417 static NumericDigit const_one_point_one_data[2] = {1, 1};
418 #endif
421 
423 {0, 0, NUMERIC_NAN, 0, NULL, NULL};
424 
425 #if DEC_DIGITS == 4
426 static const int round_powers[4] = {0, 1000, 100, 10};
427 #endif
428 
429 
430 /* ----------
431  * Local functions
432  * ----------
433  */
434 
435 #ifdef NUMERIC_DEBUG
436 static void dump_numeric(const char *str, Numeric num);
437 static void dump_var(const char *str, NumericVar *var);
438 #else
439 #define dump_numeric(s,n)
440 #define dump_var(s,v)
441 #endif
442 
443 #define digitbuf_alloc(ndigits) \
444  ((NumericDigit *) palloc((ndigits) * sizeof(NumericDigit)))
445 #define digitbuf_free(buf) \
446  do { \
447  if ((buf) != NULL) \
448  pfree(buf); \
449  } while (0)
450 
451 #define init_var(v) MemSetAligned(v, 0, sizeof(NumericVar))
452 
453 #define NUMERIC_DIGITS(num) (NUMERIC_HEADER_IS_SHORT(num) ? \
454  (num)->choice.n_short.n_data : (num)->choice.n_long.n_data)
455 #define NUMERIC_NDIGITS(num) \
456  ((VARSIZE(num) - NUMERIC_HEADER_SIZE(num)) / sizeof(NumericDigit))
457 #define NUMERIC_CAN_BE_SHORT(scale,weight) \
458  ((scale) <= NUMERIC_SHORT_DSCALE_MAX && \
459  (weight) <= NUMERIC_SHORT_WEIGHT_MAX && \
460  (weight) >= NUMERIC_SHORT_WEIGHT_MIN)
461 
462 static void alloc_var(NumericVar *var, int ndigits);
463 static void free_var(NumericVar *var);
464 static void zero_var(NumericVar *var);
465 
466 static const char *set_var_from_str(const char *str, const char *cp,
467  NumericVar *dest);
468 static void set_var_from_num(Numeric value, NumericVar *dest);
469 static void init_var_from_num(Numeric num, NumericVar *dest);
470 static void set_var_from_var(NumericVar *value, NumericVar *dest);
471 static char *get_str_from_var(NumericVar *var);
472 static char *get_str_from_var_sci(NumericVar *var, int rscale);
473 
474 static Numeric make_result(NumericVar *var);
475 
476 static void apply_typmod(NumericVar *var, int32 typmod);
477 
479 static bool numericvar_to_int64(NumericVar *var, int64 *result);
480 static void int64_to_numericvar(int64 val, NumericVar *var);
481 #ifdef HAVE_INT128
482 static bool numericvar_to_int128(NumericVar *var, int128 *result);
483 static void int128_to_numericvar(int128 val, NumericVar *var);
484 #endif
485 static double numeric_to_double_no_overflow(Numeric num);
486 static double numericvar_to_double_no_overflow(NumericVar *var);
487 
488 static Datum numeric_abbrev_convert(Datum original_datum, SortSupport ssup);
489 static bool numeric_abbrev_abort(int memtupcount, SortSupport ssup);
490 static int numeric_fast_cmp(Datum x, Datum y, SortSupport ssup);
491 static int numeric_cmp_abbrev(Datum x, Datum y, SortSupport ssup);
492 
494 
495 static int cmp_numerics(Numeric num1, Numeric num2);
496 static int cmp_var(NumericVar *var1, NumericVar *var2);
497 static int cmp_var_common(const NumericDigit *var1digits, int var1ndigits,
498  int var1weight, int var1sign,
499  const NumericDigit *var2digits, int var2ndigits,
500  int var2weight, int var2sign);
501 static void add_var(NumericVar *var1, NumericVar *var2, NumericVar *result);
502 static void sub_var(NumericVar *var1, NumericVar *var2, NumericVar *result);
503 static void mul_var(NumericVar *var1, NumericVar *var2, NumericVar *result,
504  int rscale);
505 static void div_var(NumericVar *var1, NumericVar *var2, NumericVar *result,
506  int rscale, bool round);
507 static void div_var_fast(NumericVar *var1, NumericVar *var2, NumericVar *result,
508  int rscale, bool round);
509 static int select_div_scale(NumericVar *var1, NumericVar *var2);
510 static void mod_var(NumericVar *var1, NumericVar *var2, NumericVar *result);
511 static void ceil_var(NumericVar *var, NumericVar *result);
512 static void floor_var(NumericVar *var, NumericVar *result);
513 
514 static void sqrt_var(NumericVar *arg, NumericVar *result, int rscale);
515 static void exp_var(NumericVar *arg, NumericVar *result, int rscale);
516 static int estimate_ln_dweight(NumericVar *var);
517 static void ln_var(NumericVar *arg, NumericVar *result, int rscale);
518 static void log_var(NumericVar *base, NumericVar *num, NumericVar *result);
519 static void power_var(NumericVar *base, NumericVar *exp, NumericVar *result);
520 static void power_var_int(NumericVar *base, int exp, NumericVar *result,
521  int rscale);
522 
523 static int cmp_abs(NumericVar *var1, NumericVar *var2);
524 static int cmp_abs_common(const NumericDigit *var1digits, int var1ndigits,
525  int var1weight,
526  const NumericDigit *var2digits, int var2ndigits,
527  int var2weight);
528 static void add_abs(NumericVar *var1, NumericVar *var2, NumericVar *result);
529 static void sub_abs(NumericVar *var1, NumericVar *var2, NumericVar *result);
530 static void round_var(NumericVar *var, int rscale);
531 static void trunc_var(NumericVar *var, int rscale);
532 static void strip_var(NumericVar *var);
533 static void compute_bucket(Numeric operand, Numeric bound1, Numeric bound2,
534  NumericVar *count_var, NumericVar *result_var);
535 
536 static void accum_sum_add(NumericSumAccum *accum, NumericVar *var1);
537 static void accum_sum_rescale(NumericSumAccum *accum, NumericVar *val);
538 static void accum_sum_carry(NumericSumAccum *accum);
539 static void accum_sum_reset(NumericSumAccum *accum);
540 static void accum_sum_final(NumericSumAccum *accum, NumericVar *result);
541 static void accum_sum_copy(NumericSumAccum *dst, NumericSumAccum *src);
542 static void accum_sum_combine(NumericSumAccum *accum, NumericSumAccum *accum2);
543 
544 
545 /* ----------------------------------------------------------------------
546  *
547  * Input-, output- and rounding-functions
548  *
549  * ----------------------------------------------------------------------
550  */
551 
552 
553 /*
554  * numeric_in() -
555  *
556  * Input function for numeric data type
557  */
558 Datum
560 {
561  char *str = PG_GETARG_CSTRING(0);
562 
563 #ifdef NOT_USED
564  Oid typelem = PG_GETARG_OID(1);
565 #endif
566  int32 typmod = PG_GETARG_INT32(2);
567  Numeric res;
568  const char *cp;
569 
570  /* Skip leading spaces */
571  cp = str;
572  while (*cp)
573  {
574  if (!isspace((unsigned char) *cp))
575  break;
576  cp++;
577  }
578 
579  /*
580  * Check for NaN
581  */
582  if (pg_strncasecmp(cp, "NaN", 3) == 0)
583  {
584  res = make_result(&const_nan);
585 
586  /* Should be nothing left but spaces */
587  cp += 3;
588  while (*cp)
589  {
590  if (!isspace((unsigned char) *cp))
591  ereport(ERROR,
592  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
593  errmsg("invalid input syntax for type %s: \"%s\"",
594  "numeric", str)));
595  cp++;
596  }
597  }
598  else
599  {
600  /*
601  * Use set_var_from_str() to parse a normal numeric value
602  */
604 
605  init_var(&value);
606 
607  cp = set_var_from_str(str, cp, &value);
608 
609  /*
610  * We duplicate a few lines of code here because we would like to
611  * throw any trailing-junk syntax error before any semantic error
612  * resulting from apply_typmod. We can't easily fold the two cases
613  * together because we mustn't apply apply_typmod to a NaN.
614  */
615  while (*cp)
616  {
617  if (!isspace((unsigned char) *cp))
618  ereport(ERROR,
619  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
620  errmsg("invalid input syntax for type %s: \"%s\"",
621  "numeric", str)));
622  cp++;
623  }
624 
625  apply_typmod(&value, typmod);
626 
627  res = make_result(&value);
628  free_var(&value);
629  }
630 
631  PG_RETURN_NUMERIC(res);
632 }
633 
634 
635 /*
636  * numeric_out() -
637  *
638  * Output function for numeric data type
639  */
640 Datum
642 {
643  Numeric num = PG_GETARG_NUMERIC(0);
644  NumericVar x;
645  char *str;
646 
647  /*
648  * Handle NaN
649  */
650  if (NUMERIC_IS_NAN(num))
651  PG_RETURN_CSTRING(pstrdup("NaN"));
652 
653  /*
654  * Get the number in the variable format.
655  */
656  init_var_from_num(num, &x);
657 
658  str = get_str_from_var(&x);
659 
660  PG_RETURN_CSTRING(str);
661 }
662 
663 /*
664  * numeric_is_nan() -
665  *
666  * Is Numeric value a NaN?
667  */
668 bool
670 {
671  return NUMERIC_IS_NAN(num);
672 }
673 
674 /*
675  * numeric_maximum_size() -
676  *
677  * Maximum size of a numeric with given typmod, or -1 if unlimited/unknown.
678  */
679 int32
681 {
682  int precision;
683  int numeric_digits;
684 
685  if (typmod < (int32) (VARHDRSZ))
686  return -1;
687 
688  /* precision (ie, max # of digits) is in upper bits of typmod */
689  precision = ((typmod - VARHDRSZ) >> 16) & 0xffff;
690 
691  /*
692  * This formula computes the maximum number of NumericDigits we could need
693  * in order to store the specified number of decimal digits. Because the
694  * weight is stored as a number of NumericDigits rather than a number of
695  * decimal digits, it's possible that the first NumericDigit will contain
696  * only a single decimal digit. Thus, the first two decimal digits can
697  * require two NumericDigits to store, but it isn't until we reach
698  * DEC_DIGITS + 2 decimal digits that we potentially need a third
699  * NumericDigit.
700  */
701  numeric_digits = (precision + 2 * (DEC_DIGITS - 1)) / DEC_DIGITS;
702 
703  /*
704  * In most cases, the size of a numeric will be smaller than the value
705  * computed below, because the varlena header will typically get toasted
706  * down to a single byte before being stored on disk, and it may also be
707  * possible to use a short numeric header. But our job here is to compute
708  * the worst case.
709  */
710  return NUMERIC_HDRSZ + (numeric_digits * sizeof(NumericDigit));
711 }
712 
713 /*
714  * numeric_out_sci() -
715  *
716  * Output function for numeric data type in scientific notation.
717  */
718 char *
720 {
721  NumericVar x;
722  char *str;
723 
724  /*
725  * Handle NaN
726  */
727  if (NUMERIC_IS_NAN(num))
728  return pstrdup("NaN");
729 
730  init_var_from_num(num, &x);
731 
732  str = get_str_from_var_sci(&x, scale);
733 
734  return str;
735 }
736 
737 /*
738  * numeric_normalize() -
739  *
740  * Output function for numeric data type, suppressing insignificant trailing
741  * zeroes and then any trailing decimal point. The intent of this is to
742  * produce strings that are equal if and only if the input numeric values
743  * compare equal.
744  */
745 char *
747 {
748  NumericVar x;
749  char *str;
750  int last;
751 
752  /*
753  * Handle NaN
754  */
755  if (NUMERIC_IS_NAN(num))
756  return pstrdup("NaN");
757 
758  init_var_from_num(num, &x);
759 
760  str = get_str_from_var(&x);
761 
762  /* If there's no decimal point, there's certainly nothing to remove. */
763  if (strchr(str, '.') != NULL)
764  {
765  /*
766  * Back up over trailing fractional zeroes. Since there is a decimal
767  * point, this loop will terminate safely.
768  */
769  last = strlen(str) - 1;
770  while (str[last] == '0')
771  last--;
772 
773  /* We want to get rid of the decimal point too, if it's now last. */
774  if (str[last] == '.')
775  last--;
776 
777  /* Delete whatever we backed up over. */
778  str[last + 1] = '\0';
779  }
780 
781  return str;
782 }
783 
784 /*
785  * numeric_recv - converts external binary format to numeric
786  *
787  * External format is a sequence of int16's:
788  * ndigits, weight, sign, dscale, NumericDigits.
789  */
790 Datum
792 {
794 
795 #ifdef NOT_USED
796  Oid typelem = PG_GETARG_OID(1);
797 #endif
798  int32 typmod = PG_GETARG_INT32(2);
800  Numeric res;
801  int len,
802  i;
803 
804  init_var(&value);
805 
806  len = (uint16) pq_getmsgint(buf, sizeof(uint16));
807 
808  alloc_var(&value, len);
809 
810  value.weight = (int16) pq_getmsgint(buf, sizeof(int16));
811  /* we allow any int16 for weight --- OK? */
812 
813  value.sign = (uint16) pq_getmsgint(buf, sizeof(uint16));
814  if (!(value.sign == NUMERIC_POS ||
815  value.sign == NUMERIC_NEG ||
816  value.sign == NUMERIC_NAN))
817  ereport(ERROR,
818  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
819  errmsg("invalid sign in external \"numeric\" value")));
820 
821  value.dscale = (uint16) pq_getmsgint(buf, sizeof(uint16));
822  if ((value.dscale & NUMERIC_DSCALE_MASK) != value.dscale)
823  ereport(ERROR,
824  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
825  errmsg("invalid scale in external \"numeric\" value")));
826 
827  for (i = 0; i < len; i++)
828  {
829  NumericDigit d = pq_getmsgint(buf, sizeof(NumericDigit));
830 
831  if (d < 0 || d >= NBASE)
832  ereport(ERROR,
833  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
834  errmsg("invalid digit in external \"numeric\" value")));
835  value.digits[i] = d;
836  }
837 
838  /*
839  * If the given dscale would hide any digits, truncate those digits away.
840  * We could alternatively throw an error, but that would take a bunch of
841  * extra code (about as much as trunc_var involves), and it might cause
842  * client compatibility issues.
843  */
844  trunc_var(&value, value.dscale);
845 
846  apply_typmod(&value, typmod);
847 
848  res = make_result(&value);
849  free_var(&value);
850 
851  PG_RETURN_NUMERIC(res);
852 }
853 
854 /*
855  * numeric_send - converts numeric to binary format
856  */
857 Datum
859 {
860  Numeric num = PG_GETARG_NUMERIC(0);
861  NumericVar x;
863  int i;
864 
865  init_var_from_num(num, &x);
866 
867  pq_begintypsend(&buf);
868 
869  pq_sendint(&buf, x.ndigits, sizeof(int16));
870  pq_sendint(&buf, x.weight, sizeof(int16));
871  pq_sendint(&buf, x.sign, sizeof(int16));
872  pq_sendint(&buf, x.dscale, sizeof(int16));
873  for (i = 0; i < x.ndigits; i++)
874  pq_sendint(&buf, x.digits[i], sizeof(NumericDigit));
875 
877 }
878 
879 
880 /*
881  * numeric_transform() -
882  *
883  * Flatten calls to numeric's length coercion function that solely represent
884  * increases in allowable precision. Scale changes mutate every datum, so
885  * they are unoptimizable. Some values, e.g. 1E-1001, can only fit into an
886  * unconstrained numeric, so a change from an unconstrained numeric to any
887  * constrained numeric is also unoptimizable.
888  */
889 Datum
891 {
893  Node *ret = NULL;
894  Node *typmod;
895 
896  Assert(list_length(expr->args) >= 2);
897 
898  typmod = (Node *) lsecond(expr->args);
899 
900  if (IsA(typmod, Const) &&!((Const *) typmod)->constisnull)
901  {
902  Node *source = (Node *) linitial(expr->args);
903  int32 old_typmod = exprTypmod(source);
904  int32 new_typmod = DatumGetInt32(((Const *) typmod)->constvalue);
905  int32 old_scale = (old_typmod - VARHDRSZ) & 0xffff;
906  int32 new_scale = (new_typmod - VARHDRSZ) & 0xffff;
907  int32 old_precision = (old_typmod - VARHDRSZ) >> 16 & 0xffff;
908  int32 new_precision = (new_typmod - VARHDRSZ) >> 16 & 0xffff;
909 
910  /*
911  * If new_typmod < VARHDRSZ, the destination is unconstrained; that's
912  * always OK. If old_typmod >= VARHDRSZ, the source is constrained,
913  * and we're OK if the scale is unchanged and the precision is not
914  * decreasing. See further notes in function header comment.
915  */
916  if (new_typmod < (int32) VARHDRSZ ||
917  (old_typmod >= (int32) VARHDRSZ &&
918  new_scale == old_scale && new_precision >= old_precision))
919  ret = relabel_to_typmod(source, new_typmod);
920  }
921 
922  PG_RETURN_POINTER(ret);
923 }
924 
925 /*
926  * numeric() -
927  *
928  * This is a special function called by the Postgres database system
929  * before a value is stored in a tuple's attribute. The precision and
930  * scale of the attribute have to be applied on the value.
931  */
932 Datum
934 {
935  Numeric num = PG_GETARG_NUMERIC(0);
936  int32 typmod = PG_GETARG_INT32(1);
937  Numeric new;
938  int32 tmp_typmod;
939  int precision;
940  int scale;
941  int ddigits;
942  int maxdigits;
943  NumericVar var;
944 
945  /*
946  * Handle NaN
947  */
948  if (NUMERIC_IS_NAN(num))
949  PG_RETURN_NUMERIC(make_result(&const_nan));
950 
951  /*
952  * If the value isn't a valid type modifier, simply return a copy of the
953  * input value
954  */
955  if (typmod < (int32) (VARHDRSZ))
956  {
957  new = (Numeric) palloc(VARSIZE(num));
958  memcpy(new, num, VARSIZE(num));
959  PG_RETURN_NUMERIC(new);
960  }
961 
962  /*
963  * Get the precision and scale out of the typmod value
964  */
965  tmp_typmod = typmod - VARHDRSZ;
966  precision = (tmp_typmod >> 16) & 0xffff;
967  scale = tmp_typmod & 0xffff;
968  maxdigits = precision - scale;
969 
970  /*
971  * If the number is certainly in bounds and due to the target scale no
972  * rounding could be necessary, just make a copy of the input and modify
973  * its scale fields, unless the larger scale forces us to abandon the
974  * short representation. (Note we assume the existing dscale is
975  * honest...)
976  */
977  ddigits = (NUMERIC_WEIGHT(num) + 1) * DEC_DIGITS;
978  if (ddigits <= maxdigits && scale >= NUMERIC_DSCALE(num)
979  && (NUMERIC_CAN_BE_SHORT(scale, NUMERIC_WEIGHT(num))
980  || !NUMERIC_IS_SHORT(num)))
981  {
982  new = (Numeric) palloc(VARSIZE(num));
983  memcpy(new, num, VARSIZE(num));
984  if (NUMERIC_IS_SHORT(num))
985  new->choice.n_short.n_header =
987  | (scale << NUMERIC_SHORT_DSCALE_SHIFT);
988  else
989  new->choice.n_long.n_sign_dscale = NUMERIC_SIGN(new) |
990  ((uint16) scale & NUMERIC_DSCALE_MASK);
991  PG_RETURN_NUMERIC(new);
992  }
993 
994  /*
995  * We really need to fiddle with things - unpack the number into a
996  * variable and let apply_typmod() do it.
997  */
998  init_var(&var);
999 
1000  set_var_from_num(num, &var);
1001  apply_typmod(&var, typmod);
1002  new = make_result(&var);
1003 
1004  free_var(&var);
1005 
1006  PG_RETURN_NUMERIC(new);
1007 }
1008 
1009 Datum
1011 {
1013  int32 *tl;
1014  int n;
1015  int32 typmod;
1016 
1017  tl = ArrayGetIntegerTypmods(ta, &n);
1018 
1019  if (n == 2)
1020  {
1021  if (tl[0] < 1 || tl[0] > NUMERIC_MAX_PRECISION)
1022  ereport(ERROR,
1023  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1024  errmsg("NUMERIC precision %d must be between 1 and %d",
1025  tl[0], NUMERIC_MAX_PRECISION)));
1026  if (tl[1] < 0 || tl[1] > tl[0])
1027  ereport(ERROR,
1028  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1029  errmsg("NUMERIC scale %d must be between 0 and precision %d",
1030  tl[1], tl[0])));
1031  typmod = ((tl[0] << 16) | tl[1]) + VARHDRSZ;
1032  }
1033  else if (n == 1)
1034  {
1035  if (tl[0] < 1 || tl[0] > NUMERIC_MAX_PRECISION)
1036  ereport(ERROR,
1037  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1038  errmsg("NUMERIC precision %d must be between 1 and %d",
1039  tl[0], NUMERIC_MAX_PRECISION)));
1040  /* scale defaults to zero */
1041  typmod = (tl[0] << 16) + VARHDRSZ;
1042  }
1043  else
1044  {
1045  ereport(ERROR,
1046  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1047  errmsg("invalid NUMERIC type modifier")));
1048  typmod = 0; /* keep compiler quiet */
1049  }
1050 
1051  PG_RETURN_INT32(typmod);
1052 }
1053 
1054 Datum
1056 {
1057  int32 typmod = PG_GETARG_INT32(0);
1058  char *res = (char *) palloc(64);
1059 
1060  if (typmod >= 0)
1061  snprintf(res, 64, "(%d,%d)",
1062  ((typmod - VARHDRSZ) >> 16) & 0xffff,
1063  (typmod - VARHDRSZ) & 0xffff);
1064  else
1065  *res = '\0';
1066 
1067  PG_RETURN_CSTRING(res);
1068 }
1069 
1070 
1071 /* ----------------------------------------------------------------------
1072  *
1073  * Sign manipulation, rounding and the like
1074  *
1075  * ----------------------------------------------------------------------
1076  */
1077 
1078 Datum
1080 {
1081  Numeric num = PG_GETARG_NUMERIC(0);
1082  Numeric res;
1083 
1084  /*
1085  * Handle NaN
1086  */
1087  if (NUMERIC_IS_NAN(num))
1088  PG_RETURN_NUMERIC(make_result(&const_nan));
1089 
1090  /*
1091  * Do it the easy way directly on the packed format
1092  */
1093  res = (Numeric) palloc(VARSIZE(num));
1094  memcpy(res, num, VARSIZE(num));
1095 
1096  if (NUMERIC_IS_SHORT(num))
1097  res->choice.n_short.n_header =
1099  else
1101 
1102  PG_RETURN_NUMERIC(res);
1103 }
1104 
1105 
1106 Datum
1108 {
1109  Numeric num = PG_GETARG_NUMERIC(0);
1110  Numeric res;
1111 
1112  /*
1113  * Handle NaN
1114  */
1115  if (NUMERIC_IS_NAN(num))
1116  PG_RETURN_NUMERIC(make_result(&const_nan));
1117 
1118  /*
1119  * Do it the easy way directly on the packed format
1120  */
1121  res = (Numeric) palloc(VARSIZE(num));
1122  memcpy(res, num, VARSIZE(num));
1123 
1124  /*
1125  * The packed format is known to be totally zero digit trimmed always. So
1126  * we can identify a ZERO by the fact that there are no digits at all. Do
1127  * nothing to a zero.
1128  */
1129  if (NUMERIC_NDIGITS(num) != 0)
1130  {
1131  /* Else, flip the sign */
1132  if (NUMERIC_IS_SHORT(num))
1133  res->choice.n_short.n_header =
1135  else if (NUMERIC_SIGN(num) == NUMERIC_POS)
1136  res->choice.n_long.n_sign_dscale =
1137  NUMERIC_NEG | NUMERIC_DSCALE(num);
1138  else
1139  res->choice.n_long.n_sign_dscale =
1140  NUMERIC_POS | NUMERIC_DSCALE(num);
1141  }
1142 
1143  PG_RETURN_NUMERIC(res);
1144 }
1145 
1146 
1147 Datum
1149 {
1150  Numeric num = PG_GETARG_NUMERIC(0);
1151  Numeric res;
1152 
1153  res = (Numeric) palloc(VARSIZE(num));
1154  memcpy(res, num, VARSIZE(num));
1155 
1156  PG_RETURN_NUMERIC(res);
1157 }
1158 
1159 /*
1160  * numeric_sign() -
1161  *
1162  * returns -1 if the argument is less than 0, 0 if the argument is equal
1163  * to 0, and 1 if the argument is greater than zero.
1164  */
1165 Datum
1167 {
1168  Numeric num = PG_GETARG_NUMERIC(0);
1169  Numeric res;
1171 
1172  /*
1173  * Handle NaN
1174  */
1175  if (NUMERIC_IS_NAN(num))
1176  PG_RETURN_NUMERIC(make_result(&const_nan));
1177 
1178  init_var(&result);
1179 
1180  /*
1181  * The packed format is known to be totally zero digit trimmed always. So
1182  * we can identify a ZERO by the fact that there are no digits at all.
1183  */
1184  if (NUMERIC_NDIGITS(num) == 0)
1185  set_var_from_var(&const_zero, &result);
1186  else
1187  {
1188  /*
1189  * And if there are some, we return a copy of ONE with the sign of our
1190  * argument
1191  */
1192  set_var_from_var(&const_one, &result);
1193  result.sign = NUMERIC_SIGN(num);
1194  }
1195 
1196  res = make_result(&result);
1197  free_var(&result);
1198 
1199  PG_RETURN_NUMERIC(res);
1200 }
1201 
1202 
1203 /*
1204  * numeric_round() -
1205  *
1206  * Round a value to have 'scale' digits after the decimal point.
1207  * We allow negative 'scale', implying rounding before the decimal
1208  * point --- Oracle interprets rounding that way.
1209  */
1210 Datum
1212 {
1213  Numeric num = PG_GETARG_NUMERIC(0);
1215  Numeric res;
1216  NumericVar arg;
1217 
1218  /*
1219  * Handle NaN
1220  */
1221  if (NUMERIC_IS_NAN(num))
1222  PG_RETURN_NUMERIC(make_result(&const_nan));
1223 
1224  /*
1225  * Limit the scale value to avoid possible overflow in calculations
1226  */
1227  scale = Max(scale, -NUMERIC_MAX_RESULT_SCALE);
1228  scale = Min(scale, NUMERIC_MAX_RESULT_SCALE);
1229 
1230  /*
1231  * Unpack the argument and round it at the proper digit position
1232  */
1233  init_var(&arg);
1234  set_var_from_num(num, &arg);
1235 
1236  round_var(&arg, scale);
1237 
1238  /* We don't allow negative output dscale */
1239  if (scale < 0)
1240  arg.dscale = 0;
1241 
1242  /*
1243  * Return the rounded result
1244  */
1245  res = make_result(&arg);
1246 
1247  free_var(&arg);
1248  PG_RETURN_NUMERIC(res);
1249 }
1250 
1251 
1252 /*
1253  * numeric_trunc() -
1254  *
1255  * Truncate a value to have 'scale' digits after the decimal point.
1256  * We allow negative 'scale', implying a truncation before the decimal
1257  * point --- Oracle interprets truncation that way.
1258  */
1259 Datum
1261 {
1262  Numeric num = PG_GETARG_NUMERIC(0);
1264  Numeric res;
1265  NumericVar arg;
1266 
1267  /*
1268  * Handle NaN
1269  */
1270  if (NUMERIC_IS_NAN(num))
1271  PG_RETURN_NUMERIC(make_result(&const_nan));
1272 
1273  /*
1274  * Limit the scale value to avoid possible overflow in calculations
1275  */
1276  scale = Max(scale, -NUMERIC_MAX_RESULT_SCALE);
1277  scale = Min(scale, NUMERIC_MAX_RESULT_SCALE);
1278 
1279  /*
1280  * Unpack the argument and truncate it at the proper digit position
1281  */
1282  init_var(&arg);
1283  set_var_from_num(num, &arg);
1284 
1285  trunc_var(&arg, scale);
1286 
1287  /* We don't allow negative output dscale */
1288  if (scale < 0)
1289  arg.dscale = 0;
1290 
1291  /*
1292  * Return the truncated result
1293  */
1294  res = make_result(&arg);
1295 
1296  free_var(&arg);
1297  PG_RETURN_NUMERIC(res);
1298 }
1299 
1300 
1301 /*
1302  * numeric_ceil() -
1303  *
1304  * Return the smallest integer greater than or equal to the argument
1305  */
1306 Datum
1308 {
1309  Numeric num = PG_GETARG_NUMERIC(0);
1310  Numeric res;
1312 
1313  if (NUMERIC_IS_NAN(num))
1314  PG_RETURN_NUMERIC(make_result(&const_nan));
1315 
1316  init_var_from_num(num, &result);
1317  ceil_var(&result, &result);
1318 
1319  res = make_result(&result);
1320  free_var(&result);
1321 
1322  PG_RETURN_NUMERIC(res);
1323 }
1324 
1325 
1326 /*
1327  * numeric_floor() -
1328  *
1329  * Return the largest integer equal to or less than the argument
1330  */
1331 Datum
1333 {
1334  Numeric num = PG_GETARG_NUMERIC(0);
1335  Numeric res;
1337 
1338  if (NUMERIC_IS_NAN(num))
1339  PG_RETURN_NUMERIC(make_result(&const_nan));
1340 
1341  init_var_from_num(num, &result);
1342  floor_var(&result, &result);
1343 
1344  res = make_result(&result);
1345  free_var(&result);
1346 
1347  PG_RETURN_NUMERIC(res);
1348 }
1349 
1350 
1351 /*
1352  * generate_series_numeric() -
1353  *
1354  * Generate series of numeric.
1355  */
1356 Datum
1358 {
1359  return generate_series_step_numeric(fcinfo);
1360 }
1361 
1362 Datum
1364 {
1366  FuncCallContext *funcctx;
1367  MemoryContext oldcontext;
1368 
1369  if (SRF_IS_FIRSTCALL())
1370  {
1371  Numeric start_num = PG_GETARG_NUMERIC(0);
1372  Numeric stop_num = PG_GETARG_NUMERIC(1);
1373  NumericVar steploc = const_one;
1374 
1375  /* handle NaN in start and stop values */
1376  if (NUMERIC_IS_NAN(start_num))
1377  ereport(ERROR,
1378  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1379  errmsg("start value cannot be NaN")));
1380 
1381  if (NUMERIC_IS_NAN(stop_num))
1382  ereport(ERROR,
1383  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1384  errmsg("stop value cannot be NaN")));
1385 
1386  /* see if we were given an explicit step size */
1387  if (PG_NARGS() == 3)
1388  {
1389  Numeric step_num = PG_GETARG_NUMERIC(2);
1390 
1391  if (NUMERIC_IS_NAN(step_num))
1392  ereport(ERROR,
1393  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1394  errmsg("step size cannot be NaN")));
1395 
1396  init_var_from_num(step_num, &steploc);
1397 
1398  if (cmp_var(&steploc, &const_zero) == 0)
1399  ereport(ERROR,
1400  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1401  errmsg("step size cannot equal zero")));
1402  }
1403 
1404  /* create a function context for cross-call persistence */
1405  funcctx = SRF_FIRSTCALL_INIT();
1406 
1407  /*
1408  * Switch to memory context appropriate for multiple function calls.
1409  */
1410  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1411 
1412  /* allocate memory for user context */
1413  fctx = (generate_series_numeric_fctx *)
1415 
1416  /*
1417  * Use fctx to keep state from call to call. Seed current with the
1418  * original start value. We must copy the start_num and stop_num
1419  * values rather than pointing to them, since we may have detoasted
1420  * them in the per-call context.
1421  */
1422  init_var(&fctx->current);
1423  init_var(&fctx->stop);
1424  init_var(&fctx->step);
1425 
1426  set_var_from_num(start_num, &fctx->current);
1427  set_var_from_num(stop_num, &fctx->stop);
1428  set_var_from_var(&steploc, &fctx->step);
1429 
1430  funcctx->user_fctx = fctx;
1431  MemoryContextSwitchTo(oldcontext);
1432  }
1433 
1434  /* stuff done on every call of the function */
1435  funcctx = SRF_PERCALL_SETUP();
1436 
1437  /*
1438  * Get the saved state and use current state as the result of this
1439  * iteration.
1440  */
1441  fctx = funcctx->user_fctx;
1442 
1443  if ((fctx->step.sign == NUMERIC_POS &&
1444  cmp_var(&fctx->current, &fctx->stop) <= 0) ||
1445  (fctx->step.sign == NUMERIC_NEG &&
1446  cmp_var(&fctx->current, &fctx->stop) >= 0))
1447  {
1448  Numeric result = make_result(&fctx->current);
1449 
1450  /* switch to memory context appropriate for iteration calculation */
1451  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1452 
1453  /* increment current in preparation for next iteration */
1454  add_var(&fctx->current, &fctx->step, &fctx->current);
1455  MemoryContextSwitchTo(oldcontext);
1456 
1457  /* do when there is more left to send */
1458  SRF_RETURN_NEXT(funcctx, NumericGetDatum(result));
1459  }
1460  else
1461  /* do when there is no more left */
1462  SRF_RETURN_DONE(funcctx);
1463 }
1464 
1465 
1466 /*
1467  * Implements the numeric version of the width_bucket() function
1468  * defined by SQL2003. See also width_bucket_float8().
1469  *
1470  * 'bound1' and 'bound2' are the lower and upper bounds of the
1471  * histogram's range, respectively. 'count' is the number of buckets
1472  * in the histogram. width_bucket() returns an integer indicating the
1473  * bucket number that 'operand' belongs to in an equiwidth histogram
1474  * with the specified characteristics. An operand smaller than the
1475  * lower bound is assigned to bucket 0. An operand greater than the
1476  * upper bound is assigned to an additional bucket (with number
1477  * count+1). We don't allow "NaN" for any of the numeric arguments.
1478  */
1479 Datum
1481 {
1482  Numeric operand = PG_GETARG_NUMERIC(0);
1483  Numeric bound1 = PG_GETARG_NUMERIC(1);
1484  Numeric bound2 = PG_GETARG_NUMERIC(2);
1485  int32 count = PG_GETARG_INT32(3);
1486  NumericVar count_var;
1487  NumericVar result_var;
1488  int32 result;
1489 
1490  if (count <= 0)
1491  ereport(ERROR,
1492  (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
1493  errmsg("count must be greater than zero")));
1494 
1495  if (NUMERIC_IS_NAN(operand) ||
1496  NUMERIC_IS_NAN(bound1) ||
1497  NUMERIC_IS_NAN(bound2))
1498  ereport(ERROR,
1499  (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
1500  errmsg("operand, lower bound, and upper bound cannot be NaN")));
1501 
1502  init_var(&result_var);
1503  init_var(&count_var);
1504 
1505  /* Convert 'count' to a numeric, for ease of use later */
1506  int64_to_numericvar((int64) count, &count_var);
1507 
1508  switch (cmp_numerics(bound1, bound2))
1509  {
1510  case 0:
1511  ereport(ERROR,
1512  (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
1513  errmsg("lower bound cannot equal upper bound")));
1514 
1515  /* bound1 < bound2 */
1516  case -1:
1517  if (cmp_numerics(operand, bound1) < 0)
1518  set_var_from_var(&const_zero, &result_var);
1519  else if (cmp_numerics(operand, bound2) >= 0)
1520  add_var(&count_var, &const_one, &result_var);
1521  else
1522  compute_bucket(operand, bound1, bound2,
1523  &count_var, &result_var);
1524  break;
1525 
1526  /* bound1 > bound2 */
1527  case 1:
1528  if (cmp_numerics(operand, bound1) > 0)
1529  set_var_from_var(&const_zero, &result_var);
1530  else if (cmp_numerics(operand, bound2) <= 0)
1531  add_var(&count_var, &const_one, &result_var);
1532  else
1533  compute_bucket(operand, bound1, bound2,
1534  &count_var, &result_var);
1535  break;
1536  }
1537 
1538  /* if result exceeds the range of a legal int4, we ereport here */
1539  result = numericvar_to_int32(&result_var);
1540 
1541  free_var(&count_var);
1542  free_var(&result_var);
1543 
1544  PG_RETURN_INT32(result);
1545 }
1546 
1547 /*
1548  * If 'operand' is not outside the bucket range, determine the correct
1549  * bucket for it to go. The calculations performed by this function
1550  * are derived directly from the SQL2003 spec.
1551  */
1552 static void
1553 compute_bucket(Numeric operand, Numeric bound1, Numeric bound2,
1554  NumericVar *count_var, NumericVar *result_var)
1555 {
1556  NumericVar bound1_var;
1557  NumericVar bound2_var;
1558  NumericVar operand_var;
1559 
1560  init_var_from_num(bound1, &bound1_var);
1561  init_var_from_num(bound2, &bound2_var);
1562  init_var_from_num(operand, &operand_var);
1563 
1564  if (cmp_var(&bound1_var, &bound2_var) < 0)
1565  {
1566  sub_var(&operand_var, &bound1_var, &operand_var);
1567  sub_var(&bound2_var, &bound1_var, &bound2_var);
1568  div_var(&operand_var, &bound2_var, result_var,
1569  select_div_scale(&operand_var, &bound2_var), true);
1570  }
1571  else
1572  {
1573  sub_var(&bound1_var, &operand_var, &operand_var);
1574  sub_var(&bound1_var, &bound2_var, &bound1_var);
1575  div_var(&operand_var, &bound1_var, result_var,
1576  select_div_scale(&operand_var, &bound1_var), true);
1577  }
1578 
1579  mul_var(result_var, count_var, result_var,
1580  result_var->dscale + count_var->dscale);
1581  add_var(result_var, &const_one, result_var);
1582  floor_var(result_var, result_var);
1583 
1584  free_var(&bound1_var);
1585  free_var(&bound2_var);
1586  free_var(&operand_var);
1587 }
1588 
1589 /* ----------------------------------------------------------------------
1590  *
1591  * Comparison functions
1592  *
1593  * Note: btree indexes need these routines not to leak memory; therefore,
1594  * be careful to free working copies of toasted datums. Most places don't
1595  * need to be so careful.
1596  *
1597  * Sort support:
1598  *
1599  * We implement the sortsupport strategy routine in order to get the benefit of
1600  * abbreviation. The ordinary numeric comparison can be quite slow as a result
1601  * of palloc/pfree cycles (due to detoasting packed values for alignment);
1602  * while this could be worked on itself, the abbreviation strategy gives more
1603  * speedup in many common cases.
1604  *
1605  * Two different representations are used for the abbreviated form, one in
1606  * int32 and one in int64, whichever fits into a by-value Datum. In both cases
1607  * the representation is negated relative to the original value, because we use
1608  * the largest negative value for NaN, which sorts higher than other values. We
1609  * convert the absolute value of the numeric to a 31-bit or 63-bit positive
1610  * value, and then negate it if the original number was positive.
1611  *
1612  * We abort the abbreviation process if the abbreviation cardinality is below
1613  * 0.01% of the row count (1 per 10k non-null rows). The actual break-even
1614  * point is somewhat below that, perhaps 1 per 30k (at 1 per 100k there's a
1615  * very small penalty), but we don't want to build up too many abbreviated
1616  * values before first testing for abort, so we take the slightly pessimistic
1617  * number. We make no attempt to estimate the cardinality of the real values,
1618  * since it plays no part in the cost model here (if the abbreviation is equal,
1619  * the cost of comparing equal and unequal underlying values is comparable).
1620  * We discontinue even checking for abort (saving us the hashing overhead) if
1621  * the estimated cardinality gets to 100k; that would be enough to support many
1622  * billions of rows while doing no worse than breaking even.
1623  *
1624  * ----------------------------------------------------------------------
1625  */
1626 
1627 /*
1628  * Sort support strategy routine.
1629  */
1630 Datum
1632 {
1634 
1635  ssup->comparator = numeric_fast_cmp;
1636 
1637  if (ssup->abbreviate)
1638  {
1639  NumericSortSupport *nss;
1640  MemoryContext oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
1641 
1642  nss = palloc(sizeof(NumericSortSupport));
1643 
1644  /*
1645  * palloc a buffer for handling unaligned packed values in addition to
1646  * the support struct
1647  */
1648  nss->buf = palloc(VARATT_SHORT_MAX + VARHDRSZ + 1);
1649 
1650  nss->input_count = 0;
1651  nss->estimating = true;
1652  initHyperLogLog(&nss->abbr_card, 10);
1653 
1654  ssup->ssup_extra = nss;
1655 
1656  ssup->abbrev_full_comparator = ssup->comparator;
1660 
1661  MemoryContextSwitchTo(oldcontext);
1662  }
1663 
1664  PG_RETURN_VOID();
1665 }
1666 
1667 /*
1668  * Abbreviate a numeric datum, handling NaNs and detoasting
1669  * (must not leak memory!)
1670  */
1671 static Datum
1673 {
1674  NumericSortSupport *nss = ssup->ssup_extra;
1675  void *original_varatt = PG_DETOAST_DATUM_PACKED(original_datum);
1676  Numeric value;
1677  Datum result;
1678 
1679  nss->input_count += 1;
1680 
1681  /*
1682  * This is to handle packed datums without needing a palloc/pfree cycle;
1683  * we keep and reuse a buffer large enough to handle any short datum.
1684  */
1685  if (VARATT_IS_SHORT(original_varatt))
1686  {
1687  void *buf = nss->buf;
1688  Size sz = VARSIZE_SHORT(original_varatt) - VARHDRSZ_SHORT;
1689 
1691 
1692  SET_VARSIZE(buf, VARHDRSZ + sz);
1693  memcpy(VARDATA(buf), VARDATA_SHORT(original_varatt), sz);
1694 
1695  value = (Numeric) buf;
1696  }
1697  else
1698  value = (Numeric) original_varatt;
1699 
1700  if (NUMERIC_IS_NAN(value))
1701  {
1702  result = NUMERIC_ABBREV_NAN;
1703  }
1704  else
1705  {
1706  NumericVar var;
1707 
1708  init_var_from_num(value, &var);
1709 
1710  result = numeric_abbrev_convert_var(&var, nss);
1711  }
1712 
1713  /* should happen only for external/compressed toasts */
1714  if ((Pointer) original_varatt != DatumGetPointer(original_datum))
1715  pfree(original_varatt);
1716 
1717  return result;
1718 }
1719 
1720 /*
1721  * Consider whether to abort abbreviation.
1722  *
1723  * We pay no attention to the cardinality of the non-abbreviated data. There is
1724  * no reason to do so: unlike text, we have no fast check for equal values, so
1725  * we pay the full overhead whenever the abbreviations are equal regardless of
1726  * whether the underlying values are also equal.
1727  */
1728 static bool
1729 numeric_abbrev_abort(int memtupcount, SortSupport ssup)
1730 {
1731  NumericSortSupport *nss = ssup->ssup_extra;
1732  double abbr_card;
1733 
1734  if (memtupcount < 10000 || nss->input_count < 10000 || !nss->estimating)
1735  return false;
1736 
1737  abbr_card = estimateHyperLogLog(&nss->abbr_card);
1738 
1739  /*
1740  * If we have >100k distinct values, then even if we were sorting many
1741  * billion rows we'd likely still break even, and the penalty of undoing
1742  * that many rows of abbrevs would probably not be worth it. Stop even
1743  * counting at that point.
1744  */
1745  if (abbr_card > 100000.0)
1746  {
1747 #ifdef TRACE_SORT
1748  if (trace_sort)
1749  elog(LOG,
1750  "numeric_abbrev: estimation ends at cardinality %f"
1751  " after " INT64_FORMAT " values (%d rows)",
1752  abbr_card, nss->input_count, memtupcount);
1753 #endif
1754  nss->estimating = false;
1755  return false;
1756  }
1757 
1758  /*
1759  * Target minimum cardinality is 1 per ~10k of non-null inputs. (The
1760  * break even point is somewhere between one per 100k rows, where
1761  * abbreviation has a very slight penalty, and 1 per 10k where it wins by
1762  * a measurable percentage.) We use the relatively pessimistic 10k
1763  * threshold, and add a 0.5 row fudge factor, because it allows us to
1764  * abort earlier on genuinely pathological data where we've had exactly
1765  * one abbreviated value in the first 10k (non-null) rows.
1766  */
1767  if (abbr_card < nss->input_count / 10000.0 + 0.5)
1768  {
1769 #ifdef TRACE_SORT
1770  if (trace_sort)
1771  elog(LOG,
1772  "numeric_abbrev: aborting abbreviation at cardinality %f"
1773  " below threshold %f after " INT64_FORMAT " values (%d rows)",
1774  abbr_card, nss->input_count / 10000.0 + 0.5,
1775  nss->input_count, memtupcount);
1776 #endif
1777  return true;
1778  }
1779 
1780 #ifdef TRACE_SORT
1781  if (trace_sort)
1782  elog(LOG,
1783  "numeric_abbrev: cardinality %f"
1784  " after " INT64_FORMAT " values (%d rows)",
1785  abbr_card, nss->input_count, memtupcount);
1786 #endif
1787 
1788  return false;
1789 }
1790 
1791 /*
1792  * Non-fmgr interface to the comparison routine to allow sortsupport to elide
1793  * the fmgr call. The saving here is small given how slow numeric comparisons
1794  * are, but it is a required part of the sort support API when abbreviations
1795  * are performed.
1796  *
1797  * Two palloc/pfree cycles could be saved here by using persistent buffers for
1798  * aligning short-varlena inputs, but this has not so far been considered to
1799  * be worth the effort.
1800  */
1801 static int
1803 {
1804  Numeric nx = DatumGetNumeric(x);
1805  Numeric ny = DatumGetNumeric(y);
1806  int result;
1807 
1808  result = cmp_numerics(nx, ny);
1809 
1810  if ((Pointer) nx != DatumGetPointer(x))
1811  pfree(nx);
1812  if ((Pointer) ny != DatumGetPointer(y))
1813  pfree(ny);
1814 
1815  return result;
1816 }
1817 
1818 /*
1819  * Compare abbreviations of values. (Abbreviations may be equal where the true
1820  * values differ, but if the abbreviations differ, they must reflect the
1821  * ordering of the true values.)
1822  */
1823 static int
1825 {
1826  /*
1827  * NOTE WELL: this is intentionally backwards, because the abbreviation is
1828  * negated relative to the original value, to handle NaN.
1829  */
1831  return 1;
1833  return -1;
1834  return 0;
1835 }
1836 
1837 /*
1838  * Abbreviate a NumericVar according to the available bit size.
1839  *
1840  * The 31-bit value is constructed as:
1841  *
1842  * 0 + 7bits digit weight + 24 bits digit value
1843  *
1844  * where the digit weight is in single decimal digits, not digit words, and
1845  * stored in excess-44 representation[1]. The 24-bit digit value is the 7 most
1846  * significant decimal digits of the value converted to binary. Values whose
1847  * weights would fall outside the representable range are rounded off to zero
1848  * (which is also used to represent actual zeros) or to 0x7FFFFFFF (which
1849  * otherwise cannot occur). Abbreviation therefore fails to gain any advantage
1850  * where values are outside the range 10^-44 to 10^83, which is not considered
1851  * to be a serious limitation, or when values are of the same magnitude and
1852  * equal in the first 7 decimal digits, which is considered to be an
1853  * unavoidable limitation given the available bits. (Stealing three more bits
1854  * to compare another digit would narrow the range of representable weights by
1855  * a factor of 8, which starts to look like a real limiting factor.)
1856  *
1857  * (The value 44 for the excess is essentially arbitrary)
1858  *
1859  * The 63-bit value is constructed as:
1860  *
1861  * 0 + 7bits weight + 4 x 14-bit packed digit words
1862  *
1863  * The weight in this case is again stored in excess-44, but this time it is
1864  * the original weight in digit words (i.e. powers of 10000). The first four
1865  * digit words of the value (if present; trailing zeros are assumed as needed)
1866  * are packed into 14 bits each to form the rest of the value. Again,
1867  * out-of-range values are rounded off to 0 or 0x7FFFFFFFFFFFFFFF. The
1868  * representable range in this case is 10^-176 to 10^332, which is considered
1869  * to be good enough for all practical purposes, and comparison of 4 words
1870  * means that at least 13 decimal digits are compared, which is considered to
1871  * be a reasonable compromise between effectiveness and efficiency in computing
1872  * the abbreviation.
1873  *
1874  * (The value 44 for the excess is even more arbitrary here, it was chosen just
1875  * to match the value used in the 31-bit case)
1876  *
1877  * [1] - Excess-k representation means that the value is offset by adding 'k'
1878  * and then treated as unsigned, so the smallest representable value is stored
1879  * with all bits zero. This allows simple comparisons to work on the composite
1880  * value.
1881  */
1882 
1883 #if NUMERIC_ABBREV_BITS == 64
1884 
1885 static Datum
1887 {
1888  int ndigits = var->ndigits;
1889  int weight = var->weight;
1890  int64 result;
1891 
1892  if (ndigits == 0 || weight < -44)
1893  {
1894  result = 0;
1895  }
1896  else if (weight > 83)
1897  {
1898  result = PG_INT64_MAX;
1899  }
1900  else
1901  {
1902  result = ((int64) (weight + 44) << 56);
1903 
1904  switch (ndigits)
1905  {
1906  default:
1907  result |= ((int64) var->digits[3]);
1908  /* FALLTHROUGH */
1909  case 3:
1910  result |= ((int64) var->digits[2]) << 14;
1911  /* FALLTHROUGH */
1912  case 2:
1913  result |= ((int64) var->digits[1]) << 28;
1914  /* FALLTHROUGH */
1915  case 1:
1916  result |= ((int64) var->digits[0]) << 42;
1917  break;
1918  }
1919  }
1920 
1921  /* the abbrev is negated relative to the original */
1922  if (var->sign == NUMERIC_POS)
1923  result = -result;
1924 
1925  if (nss->estimating)
1926  {
1927  uint32 tmp = ((uint32) result
1928  ^ (uint32) ((uint64) result >> 32));
1929 
1931  }
1932 
1933  return NumericAbbrevGetDatum(result);
1934 }
1935 
1936 #endif /* NUMERIC_ABBREV_BITS == 64 */
1937 
1938 #if NUMERIC_ABBREV_BITS == 32
1939 
1940 static Datum
1942 {
1943  int ndigits = var->ndigits;
1944  int weight = var->weight;
1945  int32 result;
1946 
1947  if (ndigits == 0 || weight < -11)
1948  {
1949  result = 0;
1950  }
1951  else if (weight > 20)
1952  {
1953  result = PG_INT32_MAX;
1954  }
1955  else
1956  {
1957  NumericDigit nxt1 = (ndigits > 1) ? var->digits[1] : 0;
1958 
1959  weight = (weight + 11) * 4;
1960 
1961  result = var->digits[0];
1962 
1963  /*
1964  * "result" now has 1 to 4 nonzero decimal digits. We pack in more
1965  * digits to make 7 in total (largest we can fit in 24 bits)
1966  */
1967 
1968  if (result > 999)
1969  {
1970  /* already have 4 digits, add 3 more */
1971  result = (result * 1000) + (nxt1 / 10);
1972  weight += 3;
1973  }
1974  else if (result > 99)
1975  {
1976  /* already have 3 digits, add 4 more */
1977  result = (result * 10000) + nxt1;
1978  weight += 2;
1979  }
1980  else if (result > 9)
1981  {
1982  NumericDigit nxt2 = (ndigits > 2) ? var->digits[2] : 0;
1983 
1984  /* already have 2 digits, add 5 more */
1985  result = (result * 100000) + (nxt1 * 10) + (nxt2 / 1000);
1986  weight += 1;
1987  }
1988  else
1989  {
1990  NumericDigit nxt2 = (ndigits > 2) ? var->digits[2] : 0;
1991 
1992  /* already have 1 digit, add 6 more */
1993  result = (result * 1000000) + (nxt1 * 100) + (nxt2 / 100);
1994  }
1995 
1996  result = result | (weight << 24);
1997  }
1998 
1999  /* the abbrev is negated relative to the original */
2000  if (var->sign == NUMERIC_POS)
2001  result = -result;
2002 
2003  if (nss->estimating)
2004  {
2005  uint32 tmp = (uint32) result;
2006 
2008  }
2009 
2010  return NumericAbbrevGetDatum(result);
2011 }
2012 
2013 #endif /* NUMERIC_ABBREV_BITS == 32 */
2014 
2015 /*
2016  * Ordinary (non-sortsupport) comparisons follow.
2017  */
2018 
2019 Datum
2021 {
2022  Numeric num1 = PG_GETARG_NUMERIC(0);
2023  Numeric num2 = PG_GETARG_NUMERIC(1);
2024  int result;
2025 
2026  result = cmp_numerics(num1, num2);
2027 
2028  PG_FREE_IF_COPY(num1, 0);
2029  PG_FREE_IF_COPY(num2, 1);
2030 
2031  PG_RETURN_INT32(result);
2032 }
2033 
2034 
2035 Datum
2037 {
2038  Numeric num1 = PG_GETARG_NUMERIC(0);
2039  Numeric num2 = PG_GETARG_NUMERIC(1);
2040  bool result;
2041 
2042  result = cmp_numerics(num1, num2) == 0;
2043 
2044  PG_FREE_IF_COPY(num1, 0);
2045  PG_FREE_IF_COPY(num2, 1);
2046 
2047  PG_RETURN_BOOL(result);
2048 }
2049 
2050 Datum
2052 {
2053  Numeric num1 = PG_GETARG_NUMERIC(0);
2054  Numeric num2 = PG_GETARG_NUMERIC(1);
2055  bool result;
2056 
2057  result = cmp_numerics(num1, num2) != 0;
2058 
2059  PG_FREE_IF_COPY(num1, 0);
2060  PG_FREE_IF_COPY(num2, 1);
2061 
2062  PG_RETURN_BOOL(result);
2063 }
2064 
2065 Datum
2067 {
2068  Numeric num1 = PG_GETARG_NUMERIC(0);
2069  Numeric num2 = PG_GETARG_NUMERIC(1);
2070  bool result;
2071 
2072  result = cmp_numerics(num1, num2) > 0;
2073 
2074  PG_FREE_IF_COPY(num1, 0);
2075  PG_FREE_IF_COPY(num2, 1);
2076 
2077  PG_RETURN_BOOL(result);
2078 }
2079 
2080 Datum
2082 {
2083  Numeric num1 = PG_GETARG_NUMERIC(0);
2084  Numeric num2 = PG_GETARG_NUMERIC(1);
2085  bool result;
2086 
2087  result = cmp_numerics(num1, num2) >= 0;
2088 
2089  PG_FREE_IF_COPY(num1, 0);
2090  PG_FREE_IF_COPY(num2, 1);
2091 
2092  PG_RETURN_BOOL(result);
2093 }
2094 
2095 Datum
2097 {
2098  Numeric num1 = PG_GETARG_NUMERIC(0);
2099  Numeric num2 = PG_GETARG_NUMERIC(1);
2100  bool result;
2101 
2102  result = cmp_numerics(num1, num2) < 0;
2103 
2104  PG_FREE_IF_COPY(num1, 0);
2105  PG_FREE_IF_COPY(num2, 1);
2106 
2107  PG_RETURN_BOOL(result);
2108 }
2109 
2110 Datum
2112 {
2113  Numeric num1 = PG_GETARG_NUMERIC(0);
2114  Numeric num2 = PG_GETARG_NUMERIC(1);
2115  bool result;
2116 
2117  result = cmp_numerics(num1, num2) <= 0;
2118 
2119  PG_FREE_IF_COPY(num1, 0);
2120  PG_FREE_IF_COPY(num2, 1);
2121 
2122  PG_RETURN_BOOL(result);
2123 }
2124 
2125 static int
2127 {
2128  int result;
2129 
2130  /*
2131  * We consider all NANs to be equal and larger than any non-NAN. This is
2132  * somewhat arbitrary; the important thing is to have a consistent sort
2133  * order.
2134  */
2135  if (NUMERIC_IS_NAN(num1))
2136  {
2137  if (NUMERIC_IS_NAN(num2))
2138  result = 0; /* NAN = NAN */
2139  else
2140  result = 1; /* NAN > non-NAN */
2141  }
2142  else if (NUMERIC_IS_NAN(num2))
2143  {
2144  result = -1; /* non-NAN < NAN */
2145  }
2146  else
2147  {
2148  result = cmp_var_common(NUMERIC_DIGITS(num1), NUMERIC_NDIGITS(num1),
2149  NUMERIC_WEIGHT(num1), NUMERIC_SIGN(num1),
2150  NUMERIC_DIGITS(num2), NUMERIC_NDIGITS(num2),
2151  NUMERIC_WEIGHT(num2), NUMERIC_SIGN(num2));
2152  }
2153 
2154  return result;
2155 }
2156 
2157 Datum
2159 {
2160  Numeric key = PG_GETARG_NUMERIC(0);
2161  Datum digit_hash;
2162  Datum result;
2163  int weight;
2164  int start_offset;
2165  int end_offset;
2166  int i;
2167  int hash_len;
2169 
2170  /* If it's NaN, don't try to hash the rest of the fields */
2171  if (NUMERIC_IS_NAN(key))
2172  PG_RETURN_UINT32(0);
2173 
2174  weight = NUMERIC_WEIGHT(key);
2175  start_offset = 0;
2176  end_offset = 0;
2177 
2178  /*
2179  * Omit any leading or trailing zeros from the input to the hash. The
2180  * numeric implementation *should* guarantee that leading and trailing
2181  * zeros are suppressed, but we're paranoid. Note that we measure the
2182  * starting and ending offsets in units of NumericDigits, not bytes.
2183  */
2184  digits = NUMERIC_DIGITS(key);
2185  for (i = 0; i < NUMERIC_NDIGITS(key); i++)
2186  {
2187  if (digits[i] != (NumericDigit) 0)
2188  break;
2189 
2190  start_offset++;
2191 
2192  /*
2193  * The weight is effectively the # of digits before the decimal point,
2194  * so decrement it for each leading zero we skip.
2195  */
2196  weight--;
2197  }
2198 
2199  /*
2200  * If there are no non-zero digits, then the value of the number is zero,
2201  * regardless of any other fields.
2202  */
2203  if (NUMERIC_NDIGITS(key) == start_offset)
2204  PG_RETURN_UINT32(-1);
2205 
2206  for (i = NUMERIC_NDIGITS(key) - 1; i >= 0; i--)
2207  {
2208  if (digits[i] != (NumericDigit) 0)
2209  break;
2210 
2211  end_offset++;
2212  }
2213 
2214  /* If we get here, there should be at least one non-zero digit */
2215  Assert(start_offset + end_offset < NUMERIC_NDIGITS(key));
2216 
2217  /*
2218  * Note that we don't hash on the Numeric's scale, since two numerics can
2219  * compare equal but have different scales. We also don't hash on the
2220  * sign, although we could: since a sign difference implies inequality,
2221  * this shouldn't affect correctness.
2222  */
2223  hash_len = NUMERIC_NDIGITS(key) - start_offset - end_offset;
2224  digit_hash = hash_any((unsigned char *) (NUMERIC_DIGITS(key) + start_offset),
2225  hash_len * sizeof(NumericDigit));
2226 
2227  /* Mix in the weight, via XOR */
2228  result = digit_hash ^ weight;
2229 
2230  PG_RETURN_DATUM(result);
2231 }
2232 
2233 
2234 /* ----------------------------------------------------------------------
2235  *
2236  * Basic arithmetic functions
2237  *
2238  * ----------------------------------------------------------------------
2239  */
2240 
2241 
2242 /*
2243  * numeric_add() -
2244  *
2245  * Add two numerics
2246  */
2247 Datum
2249 {
2250  Numeric num1 = PG_GETARG_NUMERIC(0);
2251  Numeric num2 = PG_GETARG_NUMERIC(1);
2252  NumericVar arg1;
2253  NumericVar arg2;
2255  Numeric res;
2256 
2257  /*
2258  * Handle NaN
2259  */
2260  if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2261  PG_RETURN_NUMERIC(make_result(&const_nan));
2262 
2263  /*
2264  * Unpack the values, let add_var() compute the result and return it.
2265  */
2266  init_var_from_num(num1, &arg1);
2267  init_var_from_num(num2, &arg2);
2268 
2269  init_var(&result);
2270  add_var(&arg1, &arg2, &result);
2271 
2272  res = make_result(&result);
2273 
2274  free_var(&result);
2275 
2276  PG_RETURN_NUMERIC(res);
2277 }
2278 
2279 
2280 /*
2281  * numeric_sub() -
2282  *
2283  * Subtract one numeric from another
2284  */
2285 Datum
2287 {
2288  Numeric num1 = PG_GETARG_NUMERIC(0);
2289  Numeric num2 = PG_GETARG_NUMERIC(1);
2290  NumericVar arg1;
2291  NumericVar arg2;
2293  Numeric res;
2294 
2295  /*
2296  * Handle NaN
2297  */
2298  if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2299  PG_RETURN_NUMERIC(make_result(&const_nan));
2300 
2301  /*
2302  * Unpack the values, let sub_var() compute the result and return it.
2303  */
2304  init_var_from_num(num1, &arg1);
2305  init_var_from_num(num2, &arg2);
2306 
2307  init_var(&result);
2308  sub_var(&arg1, &arg2, &result);
2309 
2310  res = make_result(&result);
2311 
2312  free_var(&result);
2313 
2314  PG_RETURN_NUMERIC(res);
2315 }
2316 
2317 
2318 /*
2319  * numeric_mul() -
2320  *
2321  * Calculate the product of two numerics
2322  */
2323 Datum
2325 {
2326  Numeric num1 = PG_GETARG_NUMERIC(0);
2327  Numeric num2 = PG_GETARG_NUMERIC(1);
2328  NumericVar arg1;
2329  NumericVar arg2;
2331  Numeric res;
2332 
2333  /*
2334  * Handle NaN
2335  */
2336  if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2337  PG_RETURN_NUMERIC(make_result(&const_nan));
2338 
2339  /*
2340  * Unpack the values, let mul_var() compute the result and return it.
2341  * Unlike add_var() and sub_var(), mul_var() will round its result. In the
2342  * case of numeric_mul(), which is invoked for the * operator on numerics,
2343  * we request exact representation for the product (rscale = sum(dscale of
2344  * arg1, dscale of arg2)).
2345  */
2346  init_var_from_num(num1, &arg1);
2347  init_var_from_num(num2, &arg2);
2348 
2349  init_var(&result);
2350  mul_var(&arg1, &arg2, &result, arg1.dscale + arg2.dscale);
2351 
2352  res = make_result(&result);
2353 
2354  free_var(&result);
2355 
2356  PG_RETURN_NUMERIC(res);
2357 }
2358 
2359 
2360 /*
2361  * numeric_div() -
2362  *
2363  * Divide one numeric into another
2364  */
2365 Datum
2367 {
2368  Numeric num1 = PG_GETARG_NUMERIC(0);
2369  Numeric num2 = PG_GETARG_NUMERIC(1);
2370  NumericVar arg1;
2371  NumericVar arg2;
2373  Numeric res;
2374  int rscale;
2375 
2376  /*
2377  * Handle NaN
2378  */
2379  if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2380  PG_RETURN_NUMERIC(make_result(&const_nan));
2381 
2382  /*
2383  * Unpack the arguments
2384  */
2385  init_var_from_num(num1, &arg1);
2386  init_var_from_num(num2, &arg2);
2387 
2388  init_var(&result);
2389 
2390  /*
2391  * Select scale for division result
2392  */
2393  rscale = select_div_scale(&arg1, &arg2);
2394 
2395  /*
2396  * Do the divide and return the result
2397  */
2398  div_var(&arg1, &arg2, &result, rscale, true);
2399 
2400  res = make_result(&result);
2401 
2402  free_var(&result);
2403 
2404  PG_RETURN_NUMERIC(res);
2405 }
2406 
2407 
2408 /*
2409  * numeric_div_trunc() -
2410  *
2411  * Divide one numeric into another, truncating the result to an integer
2412  */
2413 Datum
2415 {
2416  Numeric num1 = PG_GETARG_NUMERIC(0);
2417  Numeric num2 = PG_GETARG_NUMERIC(1);
2418  NumericVar arg1;
2419  NumericVar arg2;
2421  Numeric res;
2422 
2423  /*
2424  * Handle NaN
2425  */
2426  if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2427  PG_RETURN_NUMERIC(make_result(&const_nan));
2428 
2429  /*
2430  * Unpack the arguments
2431  */
2432  init_var_from_num(num1, &arg1);
2433  init_var_from_num(num2, &arg2);
2434 
2435  init_var(&result);
2436 
2437  /*
2438  * Do the divide and return the result
2439  */
2440  div_var(&arg1, &arg2, &result, 0, false);
2441 
2442  res = make_result(&result);
2443 
2444  free_var(&result);
2445 
2446  PG_RETURN_NUMERIC(res);
2447 }
2448 
2449 
2450 /*
2451  * numeric_mod() -
2452  *
2453  * Calculate the modulo of two numerics
2454  */
2455 Datum
2457 {
2458  Numeric num1 = PG_GETARG_NUMERIC(0);
2459  Numeric num2 = PG_GETARG_NUMERIC(1);
2460  Numeric res;
2461  NumericVar arg1;
2462  NumericVar arg2;
2464 
2465  if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2466  PG_RETURN_NUMERIC(make_result(&const_nan));
2467 
2468  init_var_from_num(num1, &arg1);
2469  init_var_from_num(num2, &arg2);
2470 
2471  init_var(&result);
2472 
2473  mod_var(&arg1, &arg2, &result);
2474 
2475  res = make_result(&result);
2476 
2477  free_var(&result);
2478 
2479  PG_RETURN_NUMERIC(res);
2480 }
2481 
2482 
2483 /*
2484  * numeric_inc() -
2485  *
2486  * Increment a number by one
2487  */
2488 Datum
2490 {
2491  Numeric num = PG_GETARG_NUMERIC(0);
2492  NumericVar arg;
2493  Numeric res;
2494 
2495  /*
2496  * Handle NaN
2497  */
2498  if (NUMERIC_IS_NAN(num))
2499  PG_RETURN_NUMERIC(make_result(&const_nan));
2500 
2501  /*
2502  * Compute the result and return it
2503  */
2504  init_var_from_num(num, &arg);
2505 
2506  add_var(&arg, &const_one, &arg);
2507 
2508  res = make_result(&arg);
2509 
2510  free_var(&arg);
2511 
2512  PG_RETURN_NUMERIC(res);
2513 }
2514 
2515 
2516 /*
2517  * numeric_smaller() -
2518  *
2519  * Return the smaller of two numbers
2520  */
2521 Datum
2523 {
2524  Numeric num1 = PG_GETARG_NUMERIC(0);
2525  Numeric num2 = PG_GETARG_NUMERIC(1);
2526 
2527  /*
2528  * Use cmp_numerics so that this will agree with the comparison operators,
2529  * particularly as regards comparisons involving NaN.
2530  */
2531  if (cmp_numerics(num1, num2) < 0)
2532  PG_RETURN_NUMERIC(num1);
2533  else
2534  PG_RETURN_NUMERIC(num2);
2535 }
2536 
2537 
2538 /*
2539  * numeric_larger() -
2540  *
2541  * Return the larger of two numbers
2542  */
2543 Datum
2545 {
2546  Numeric num1 = PG_GETARG_NUMERIC(0);
2547  Numeric num2 = PG_GETARG_NUMERIC(1);
2548 
2549  /*
2550  * Use cmp_numerics so that this will agree with the comparison operators,
2551  * particularly as regards comparisons involving NaN.
2552  */
2553  if (cmp_numerics(num1, num2) > 0)
2554  PG_RETURN_NUMERIC(num1);
2555  else
2556  PG_RETURN_NUMERIC(num2);
2557 }
2558 
2559 
2560 /* ----------------------------------------------------------------------
2561  *
2562  * Advanced math functions
2563  *
2564  * ----------------------------------------------------------------------
2565  */
2566 
2567 /*
2568  * numeric_fac()
2569  *
2570  * Compute factorial
2571  */
2572 Datum
2574 {
2575  int64 num = PG_GETARG_INT64(0);
2576  Numeric res;
2577  NumericVar fact;
2579 
2580  if (num <= 1)
2581  {
2582  res = make_result(&const_one);
2583  PG_RETURN_NUMERIC(res);
2584  }
2585  /* Fail immediately if the result would overflow */
2586  if (num > 32177)
2587  ereport(ERROR,
2588  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
2589  errmsg("value overflows numeric format")));
2590 
2591  init_var(&fact);
2592  init_var(&result);
2593 
2594  int64_to_numericvar(num, &result);
2595 
2596  for (num = num - 1; num > 1; num--)
2597  {
2598  /* this loop can take awhile, so allow it to be interrupted */
2600 
2601  int64_to_numericvar(num, &fact);
2602 
2603  mul_var(&result, &fact, &result, 0);
2604  }
2605 
2606  res = make_result(&result);
2607 
2608  free_var(&fact);
2609  free_var(&result);
2610 
2611  PG_RETURN_NUMERIC(res);
2612 }
2613 
2614 
2615 /*
2616  * numeric_sqrt() -
2617  *
2618  * Compute the square root of a numeric.
2619  */
2620 Datum
2622 {
2623  Numeric num = PG_GETARG_NUMERIC(0);
2624  Numeric res;
2625  NumericVar arg;
2627  int sweight;
2628  int rscale;
2629 
2630  /*
2631  * Handle NaN
2632  */
2633  if (NUMERIC_IS_NAN(num))
2634  PG_RETURN_NUMERIC(make_result(&const_nan));
2635 
2636  /*
2637  * Unpack the argument and determine the result scale. We choose a scale
2638  * to give at least NUMERIC_MIN_SIG_DIGITS significant digits; but in any
2639  * case not less than the input's dscale.
2640  */
2641  init_var_from_num(num, &arg);
2642 
2643  init_var(&result);
2644 
2645  /* Assume the input was normalized, so arg.weight is accurate */
2646  sweight = (arg.weight + 1) * DEC_DIGITS / 2 - 1;
2647 
2648  rscale = NUMERIC_MIN_SIG_DIGITS - sweight;
2649  rscale = Max(rscale, arg.dscale);
2650  rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
2651  rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
2652 
2653  /*
2654  * Let sqrt_var() do the calculation and return the result.
2655  */
2656  sqrt_var(&arg, &result, rscale);
2657 
2658  res = make_result(&result);
2659 
2660  free_var(&result);
2661 
2662  PG_RETURN_NUMERIC(res);
2663 }
2664 
2665 
2666 /*
2667  * numeric_exp() -
2668  *
2669  * Raise e to the power of x
2670  */
2671 Datum
2673 {
2674  Numeric num = PG_GETARG_NUMERIC(0);
2675  Numeric res;
2676  NumericVar arg;
2678  int rscale;
2679  double val;
2680 
2681  /*
2682  * Handle NaN
2683  */
2684  if (NUMERIC_IS_NAN(num))
2685  PG_RETURN_NUMERIC(make_result(&const_nan));
2686 
2687  /*
2688  * Unpack the argument and determine the result scale. We choose a scale
2689  * to give at least NUMERIC_MIN_SIG_DIGITS significant digits; but in any
2690  * case not less than the input's dscale.
2691  */
2692  init_var_from_num(num, &arg);
2693 
2694  init_var(&result);
2695 
2696  /* convert input to float8, ignoring overflow */
2698 
2699  /*
2700  * log10(result) = num * log10(e), so this is approximately the decimal
2701  * weight of the result:
2702  */
2703  val *= 0.434294481903252;
2704 
2705  /* limit to something that won't cause integer overflow */
2706  val = Max(val, -NUMERIC_MAX_RESULT_SCALE);
2707  val = Min(val, NUMERIC_MAX_RESULT_SCALE);
2708 
2709  rscale = NUMERIC_MIN_SIG_DIGITS - (int) val;
2710  rscale = Max(rscale, arg.dscale);
2711  rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
2712  rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
2713 
2714  /*
2715  * Let exp_var() do the calculation and return the result.
2716  */
2717  exp_var(&arg, &result, rscale);
2718 
2719  res = make_result(&result);
2720 
2721  free_var(&result);
2722 
2723  PG_RETURN_NUMERIC(res);
2724 }
2725 
2726 
2727 /*
2728  * numeric_ln() -
2729  *
2730  * Compute the natural logarithm of x
2731  */
2732 Datum
2734 {
2735  Numeric num = PG_GETARG_NUMERIC(0);
2736  Numeric res;
2737  NumericVar arg;
2739  int ln_dweight;
2740  int rscale;
2741 
2742  /*
2743  * Handle NaN
2744  */
2745  if (NUMERIC_IS_NAN(num))
2746  PG_RETURN_NUMERIC(make_result(&const_nan));
2747 
2748  init_var_from_num(num, &arg);
2749  init_var(&result);
2750 
2751  /* Estimated dweight of logarithm */
2752  ln_dweight = estimate_ln_dweight(&arg);
2753 
2754  rscale = NUMERIC_MIN_SIG_DIGITS - ln_dweight;
2755  rscale = Max(rscale, arg.dscale);
2756  rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
2757  rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
2758 
2759  ln_var(&arg, &result, rscale);
2760 
2761  res = make_result(&result);
2762 
2763  free_var(&result);
2764 
2765  PG_RETURN_NUMERIC(res);
2766 }
2767 
2768 
2769 /*
2770  * numeric_log() -
2771  *
2772  * Compute the logarithm of x in a given base
2773  */
2774 Datum
2776 {
2777  Numeric num1 = PG_GETARG_NUMERIC(0);
2778  Numeric num2 = PG_GETARG_NUMERIC(1);
2779  Numeric res;
2780  NumericVar arg1;
2781  NumericVar arg2;
2783 
2784  /*
2785  * Handle NaN
2786  */
2787  if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2788  PG_RETURN_NUMERIC(make_result(&const_nan));
2789 
2790  /*
2791  * Initialize things
2792  */
2793  init_var_from_num(num1, &arg1);
2794  init_var_from_num(num2, &arg2);
2795  init_var(&result);
2796 
2797  /*
2798  * Call log_var() to compute and return the result; note it handles scale
2799  * selection itself.
2800  */
2801  log_var(&arg1, &arg2, &result);
2802 
2803  res = make_result(&result);
2804 
2805  free_var(&result);
2806 
2807  PG_RETURN_NUMERIC(res);
2808 }
2809 
2810 
2811 /*
2812  * numeric_power() -
2813  *
2814  * Raise b to the power of x
2815  */
2816 Datum
2818 {
2819  Numeric num1 = PG_GETARG_NUMERIC(0);
2820  Numeric num2 = PG_GETARG_NUMERIC(1);
2821  Numeric res;
2822  NumericVar arg1;
2823  NumericVar arg2;
2824  NumericVar arg2_trunc;
2826 
2827  /*
2828  * Handle NaN
2829  */
2830  if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2831  PG_RETURN_NUMERIC(make_result(&const_nan));
2832 
2833  /*
2834  * Initialize things
2835  */
2836  init_var(&arg2_trunc);
2837  init_var(&result);
2838  init_var_from_num(num1, &arg1);
2839  init_var_from_num(num2, &arg2);
2840 
2841  set_var_from_var(&arg2, &arg2_trunc);
2842  trunc_var(&arg2_trunc, 0);
2843 
2844  /*
2845  * The SQL spec requires that we emit a particular SQLSTATE error code for
2846  * certain error conditions. Specifically, we don't return a
2847  * divide-by-zero error code for 0 ^ -1.
2848  */
2849  if (cmp_var(&arg1, &const_zero) == 0 &&
2850  cmp_var(&arg2, &const_zero) < 0)
2851  ereport(ERROR,
2852  (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
2853  errmsg("zero raised to a negative power is undefined")));
2854 
2855  if (cmp_var(&arg1, &const_zero) < 0 &&
2856  cmp_var(&arg2, &arg2_trunc) != 0)
2857  ereport(ERROR,
2858  (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
2859  errmsg("a negative number raised to a non-integer power yields a complex result")));
2860 
2861  /*
2862  * Call power_var() to compute and return the result; note it handles
2863  * scale selection itself.
2864  */
2865  power_var(&arg1, &arg2, &result);
2866 
2867  res = make_result(&result);
2868 
2869  free_var(&result);
2870  free_var(&arg2_trunc);
2871 
2872  PG_RETURN_NUMERIC(res);
2873 }
2874 
2875 /*
2876  * numeric_scale() -
2877  *
2878  * Returns the scale, i.e. the count of decimal digits in the fractional part
2879  */
2880 Datum
2882 {
2883  Numeric num = PG_GETARG_NUMERIC(0);
2884 
2885  if (NUMERIC_IS_NAN(num))
2886  PG_RETURN_NULL();
2887 
2889 }
2890 
2891 
2892 
2893 /* ----------------------------------------------------------------------
2894  *
2895  * Type conversion functions
2896  *
2897  * ----------------------------------------------------------------------
2898  */
2899 
2900 
2901 Datum
2903 {
2904  int32 val = PG_GETARG_INT32(0);
2905  Numeric res;
2907 
2908  init_var(&result);
2909 
2910  int64_to_numericvar((int64) val, &result);
2911 
2912  res = make_result(&result);
2913 
2914  free_var(&result);
2915 
2916  PG_RETURN_NUMERIC(res);
2917 }
2918 
2919 
2920 Datum
2922 {
2923  Numeric num = PG_GETARG_NUMERIC(0);
2924  NumericVar x;
2925  int32 result;
2926 
2927  /* XXX would it be better to return NULL? */
2928  if (NUMERIC_IS_NAN(num))
2929  ereport(ERROR,
2930  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2931  errmsg("cannot convert NaN to integer")));
2932 
2933  /* Convert to variable format, then convert to int4 */
2934  init_var_from_num(num, &x);
2935  result = numericvar_to_int32(&x);
2936  PG_RETURN_INT32(result);
2937 }
2938 
2939 /*
2940  * Given a NumericVar, convert it to an int32. If the NumericVar
2941  * exceeds the range of an int32, raise the appropriate error via
2942  * ereport(). The input NumericVar is *not* free'd.
2943  */
2944 static int32
2946 {
2947  int32 result;
2948  int64 val;
2949 
2950  if (!numericvar_to_int64(var, &val))
2951  ereport(ERROR,
2952  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
2953  errmsg("integer out of range")));
2954 
2955  /* Down-convert to int4 */
2956  result = (int32) val;
2957 
2958  /* Test for overflow by reverse-conversion. */
2959  if ((int64) result != val)
2960  ereport(ERROR,
2961  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
2962  errmsg("integer out of range")));
2963 
2964  return result;
2965 }
2966 
2967 Datum
2969 {
2970  int64 val = PG_GETARG_INT64(0);
2971  Numeric res;
2973 
2974  init_var(&result);
2975 
2976  int64_to_numericvar(val, &result);
2977 
2978  res = make_result(&result);
2979 
2980  free_var(&result);
2981 
2982  PG_RETURN_NUMERIC(res);
2983 }
2984 
2985 
2986 Datum
2988 {
2989  Numeric num = PG_GETARG_NUMERIC(0);
2990  NumericVar x;
2991  int64 result;
2992 
2993  /* XXX would it be better to return NULL? */
2994  if (NUMERIC_IS_NAN(num))
2995  ereport(ERROR,
2996  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2997  errmsg("cannot convert NaN to bigint")));
2998 
2999  /* Convert to variable format and thence to int8 */
3000  init_var_from_num(num, &x);
3001 
3002  if (!numericvar_to_int64(&x, &result))
3003  ereport(ERROR,
3004  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
3005  errmsg("bigint out of range")));
3006 
3007  PG_RETURN_INT64(result);
3008 }
3009 
3010 
3011 Datum
3013 {
3014  int16 val = PG_GETARG_INT16(0);
3015  Numeric res;
3017 
3018  init_var(&result);
3019 
3020  int64_to_numericvar((int64) val, &result);
3021 
3022  res = make_result(&result);
3023 
3024  free_var(&result);
3025 
3026  PG_RETURN_NUMERIC(res);
3027 }
3028 
3029 
3030 Datum
3032 {
3033  Numeric num = PG_GETARG_NUMERIC(0);
3034  NumericVar x;
3035  int64 val;
3036  int16 result;
3037 
3038  /* XXX would it be better to return NULL? */
3039  if (NUMERIC_IS_NAN(num))
3040  ereport(ERROR,
3041  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3042  errmsg("cannot convert NaN to smallint")));
3043 
3044  /* Convert to variable format and thence to int8 */
3045  init_var_from_num(num, &x);
3046 
3047  if (!numericvar_to_int64(&x, &val))
3048  ereport(ERROR,
3049  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
3050  errmsg("smallint out of range")));
3051 
3052  /* Down-convert to int2 */
3053  result = (int16) val;
3054 
3055  /* Test for overflow by reverse-conversion. */
3056  if ((int64) result != val)
3057  ereport(ERROR,
3058  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
3059  errmsg("smallint out of range")));
3060 
3061  PG_RETURN_INT16(result);
3062 }
3063 
3064 
3065 Datum
3067 {
3069  Numeric res;
3071  char buf[DBL_DIG + 100];
3072 
3073  if (isnan(val))
3074  PG_RETURN_NUMERIC(make_result(&const_nan));
3075 
3076  sprintf(buf, "%.*g", DBL_DIG, val);
3077 
3078  init_var(&result);
3079 
3080  /* Assume we need not worry about leading/trailing spaces */
3081  (void) set_var_from_str(buf, buf, &result);
3082 
3083  res = make_result(&result);
3084 
3085  free_var(&result);
3086 
3087  PG_RETURN_NUMERIC(res);
3088 }
3089 
3090 
3091 Datum
3093 {
3094  Numeric num = PG_GETARG_NUMERIC(0);
3095  char *tmp;
3096  Datum result;
3097 
3098  if (NUMERIC_IS_NAN(num))
3100 
3102  NumericGetDatum(num)));
3103 
3105 
3106  pfree(tmp);
3107 
3108  PG_RETURN_DATUM(result);
3109 }
3110 
3111 
3112 /*
3113  * Convert numeric to float8; if out of range, return +/- HUGE_VAL
3114  *
3115  * (internal helper function, not directly callable from SQL)
3116  */
3117 Datum
3119 {
3120  Numeric num = PG_GETARG_NUMERIC(0);
3121  double val;
3122 
3123  if (NUMERIC_IS_NAN(num))
3125 
3126  val = numeric_to_double_no_overflow(num);
3127 
3128  PG_RETURN_FLOAT8(val);
3129 }
3130 
3131 Datum
3133 {
3135  Numeric res;
3137  char buf[FLT_DIG + 100];
3138 
3139  if (isnan(val))
3140  PG_RETURN_NUMERIC(make_result(&const_nan));
3141 
3142  sprintf(buf, "%.*g", FLT_DIG, val);
3143 
3144  init_var(&result);
3145 
3146  /* Assume we need not worry about leading/trailing spaces */
3147  (void) set_var_from_str(buf, buf, &result);
3148 
3149  res = make_result(&result);
3150 
3151  free_var(&result);
3152 
3153  PG_RETURN_NUMERIC(res);
3154 }
3155 
3156 
3157 Datum
3159 {
3160  Numeric num = PG_GETARG_NUMERIC(0);
3161  char *tmp;
3162  Datum result;
3163 
3164  if (NUMERIC_IS_NAN(num))
3166 
3168  NumericGetDatum(num)));
3169 
3171 
3172  pfree(tmp);
3173 
3174  PG_RETURN_DATUM(result);
3175 }
3176 
3177 
3178 /* ----------------------------------------------------------------------
3179  *
3180  * Aggregate functions
3181  *
3182  * The transition datatype for all these aggregates is declared as INTERNAL.
3183  * Actually, it's a pointer to a NumericAggState allocated in the aggregate
3184  * context. The digit buffers for the NumericVars will be there too.
3185  *
3186  * On platforms which support 128-bit integers some aggregates instead use a
3187  * 128-bit integer based transition datatype to speed up calculations.
3188  *
3189  * ----------------------------------------------------------------------
3190  */
3191 
3192 typedef struct NumericAggState
3193 {
3194  bool calcSumX2; /* if true, calculate sumX2 */
3195  MemoryContext agg_context; /* context we're calculating in */
3196  int64 N; /* count of processed numbers */
3197  NumericSumAccum sumX; /* sum of processed numbers */
3198  NumericSumAccum sumX2; /* sum of squares of processed numbers */
3199  int maxScale; /* maximum scale seen so far */
3200  int64 maxScaleCount; /* number of values seen with maximum scale */
3201  int64 NaNcount; /* count of NaN values (not included in N!) */
3202 } NumericAggState;
3203 
3204 /*
3205  * Prepare state data for a numeric aggregate function that needs to compute
3206  * sum, count and optionally sum of squares of the input.
3207  */
3208 static NumericAggState *
3209 makeNumericAggState(FunctionCallInfo fcinfo, bool calcSumX2)
3210 {
3212  MemoryContext agg_context;
3213  MemoryContext old_context;
3214 
3215  if (!AggCheckCallContext(fcinfo, &agg_context))
3216  elog(ERROR, "aggregate function called in non-aggregate context");
3217 
3218  old_context = MemoryContextSwitchTo(agg_context);
3219 
3220  state = (NumericAggState *) palloc0(sizeof(NumericAggState));
3221  state->calcSumX2 = calcSumX2;
3222  state->agg_context = agg_context;
3223 
3224  MemoryContextSwitchTo(old_context);
3225 
3226  return state;
3227 }
3228 
3229 /*
3230  * Like makeNumericAggState(), but allocate the state in the current memory
3231  * context.
3232  */
3233 static NumericAggState *
3235 {
3237 
3238  state = (NumericAggState *) palloc0(sizeof(NumericAggState));
3239  state->calcSumX2 = calcSumX2;
3241 
3242  return state;
3243 }
3244 
3245 /*
3246  * Accumulate a new input value for numeric aggregate functions.
3247  */
3248 static void
3250 {
3251  NumericVar X;
3252  NumericVar X2;
3253  MemoryContext old_context;
3254 
3255  /* Count NaN inputs separately from all else */
3256  if (NUMERIC_IS_NAN(newval))
3257  {
3258  state->NaNcount++;
3259  return;
3260  }
3261 
3262  /* load processed number in short-lived context */
3263  init_var_from_num(newval, &X);
3264 
3265  /*
3266  * Track the highest input dscale that we've seen, to support inverse
3267  * transitions (see do_numeric_discard).
3268  */
3269  if (X.dscale > state->maxScale)
3270  {
3271  state->maxScale = X.dscale;
3272  state->maxScaleCount = 1;
3273  }
3274  else if (X.dscale == state->maxScale)
3275  state->maxScaleCount++;
3276 
3277  /* if we need X^2, calculate that in short-lived context */
3278  if (state->calcSumX2)
3279  {
3280  init_var(&X2);
3281  mul_var(&X, &X, &X2, X.dscale * 2);
3282  }
3283 
3284  /* The rest of this needs to work in the aggregate context */
3285  old_context = MemoryContextSwitchTo(state->agg_context);
3286 
3287  state->N++;
3288 
3289  /* Accumulate sums */
3290  accum_sum_add(&(state->sumX), &X);
3291 
3292  if (state->calcSumX2)
3293  accum_sum_add(&(state->sumX2), &X2);
3294 
3295  MemoryContextSwitchTo(old_context);
3296 }
3297 
3298 /*
3299  * Attempt to remove an input value from the aggregated state.
3300  *
3301  * If the value cannot be removed then the function will return false; the
3302  * possible reasons for failing are described below.
3303  *
3304  * If we aggregate the values 1.01 and 2 then the result will be 3.01.
3305  * If we are then asked to un-aggregate the 1.01 then we must fail as we
3306  * won't be able to tell what the new aggregated value's dscale should be.
3307  * We don't want to return 2.00 (dscale = 2), since the sum's dscale would
3308  * have been zero if we'd really aggregated only 2.
3309  *
3310  * Note: alternatively, we could count the number of inputs with each possible
3311  * dscale (up to some sane limit). Not yet clear if it's worth the trouble.
3312  */
3313 static bool
3315 {
3316  NumericVar X;
3317  NumericVar X2;
3318  MemoryContext old_context;
3319 
3320  /* Count NaN inputs separately from all else */
3321  if (NUMERIC_IS_NAN(newval))
3322  {
3323  state->NaNcount--;
3324  return true;
3325  }
3326 
3327  /* load processed number in short-lived context */
3328  init_var_from_num(newval, &X);
3329 
3330  /*
3331  * state->sumX's dscale is the maximum dscale of any of the inputs.
3332  * Removing the last input with that dscale would require us to recompute
3333  * the maximum dscale of the *remaining* inputs, which we cannot do unless
3334  * no more non-NaN inputs remain at all. So we report a failure instead,
3335  * and force the aggregation to be redone from scratch.
3336  */
3337  if (X.dscale == state->maxScale)
3338  {
3339  if (state->maxScaleCount > 1 || state->maxScale == 0)
3340  {
3341  /*
3342  * Some remaining inputs have same dscale, or dscale hasn't gotten
3343  * above zero anyway
3344  */
3345  state->maxScaleCount--;
3346  }
3347  else if (state->N == 1)
3348  {
3349  /* No remaining non-NaN inputs at all, so reset maxScale */
3350  state->maxScale = 0;
3351  state->maxScaleCount = 0;
3352  }
3353  else
3354  {
3355  /* Correct new maxScale is uncertain, must fail */
3356  return false;
3357  }
3358  }
3359 
3360  /* if we need X^2, calculate that in short-lived context */
3361  if (state->calcSumX2)
3362  {
3363  init_var(&X2);
3364  mul_var(&X, &X, &X2, X.dscale * 2);
3365  }
3366 
3367  /* The rest of this needs to work in the aggregate context */
3368  old_context = MemoryContextSwitchTo(state->agg_context);
3369 
3370  if (state->N-- > 1)
3371  {
3372  /* Negate X, to subtract it from the sum */
3373  X.sign = (X.sign == NUMERIC_POS ? NUMERIC_NEG : NUMERIC_POS);
3374  accum_sum_add(&(state->sumX), &X);
3375 
3376  if (state->calcSumX2)
3377  {
3378  /* Negate X^2. X^2 is always positive */
3379  X2.sign = NUMERIC_NEG;
3380  accum_sum_add(&(state->sumX2), &X2);
3381  }
3382  }
3383  else
3384  {
3385  /* Zero the sums */
3386  Assert(state->N == 0);
3387 
3388  accum_sum_reset(&state->sumX);
3389  if (state->calcSumX2)
3390  accum_sum_reset(&state->sumX2);
3391  }
3392 
3393  MemoryContextSwitchTo(old_context);
3394 
3395  return true;
3396 }
3397 
3398 /*
3399  * Generic transition function for numeric aggregates that require sumX2.
3400  */
3401 Datum
3403 {
3405 
3406  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
3407 
3408  /* Create the state data on the first call */
3409  if (state == NULL)
3410  state = makeNumericAggState(fcinfo, true);
3411 
3412  if (!PG_ARGISNULL(1))
3414 
3415  PG_RETURN_POINTER(state);
3416 }
3417 
3418 /*
3419  * Generic combine function for numeric aggregates which require sumX2
3420  */
3421 Datum
3423 {
3424  NumericAggState *state1;
3425  NumericAggState *state2;
3426  MemoryContext agg_context;
3427  MemoryContext old_context;
3428 
3429  if (!AggCheckCallContext(fcinfo, &agg_context))
3430  elog(ERROR, "aggregate function called in non-aggregate context");
3431 
3432  state1 = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
3433  state2 = PG_ARGISNULL(1) ? NULL : (NumericAggState *) PG_GETARG_POINTER(1);
3434 
3435  if (state2 == NULL)
3436  PG_RETURN_POINTER(state1);
3437 
3438  /* manually copy all fields from state2 to state1 */
3439  if (state1 == NULL)
3440  {
3441  old_context = MemoryContextSwitchTo(agg_context);
3442 
3443  state1 = makeNumericAggStateCurrentContext(true);
3444  state1->N = state2->N;
3445  state1->NaNcount = state2->NaNcount;
3446  state1->maxScale = state2->maxScale;
3447  state1->maxScaleCount = state2->maxScaleCount;
3448 
3449  accum_sum_copy(&state1->sumX, &state2->sumX);
3450  accum_sum_copy(&state1->sumX2, &state2->sumX2);
3451 
3452  MemoryContextSwitchTo(old_context);
3453 
3454  PG_RETURN_POINTER(state1);
3455  }
3456 
3457  if (state2->N > 0)
3458  {
3459  state1->N += state2->N;
3460  state1->NaNcount += state2->NaNcount;
3461 
3462  /*
3463  * These are currently only needed for moving aggregates, but let's do
3464  * the right thing anyway...
3465  */
3466  if (state2->maxScale > state1->maxScale)
3467  {
3468  state1->maxScale = state2->maxScale;
3469  state1->maxScaleCount = state2->maxScaleCount;
3470  }
3471  else if (state2->maxScale == state1->maxScale)
3472  state1->maxScaleCount += state2->maxScaleCount;
3473 
3474  /* The rest of this needs to work in the aggregate context */
3475  old_context = MemoryContextSwitchTo(agg_context);
3476 
3477  /* Accumulate sums */
3478  accum_sum_combine(&state1->sumX, &state2->sumX);
3479  accum_sum_combine(&state1->sumX2, &state2->sumX2);
3480 
3481  MemoryContextSwitchTo(old_context);
3482  }
3483  PG_RETURN_POINTER(state1);
3484 }
3485 
3486 /*
3487  * Generic transition function for numeric aggregates that don't require sumX2.
3488  */
3489 Datum
3491 {
3493 
3494  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
3495 
3496  /* Create the state data on the first call */
3497  if (state == NULL)
3498  state = makeNumericAggState(fcinfo, false);
3499 
3500  if (!PG_ARGISNULL(1))
3502 
3503  PG_RETURN_POINTER(state);
3504 }
3505 
3506 /*
3507  * Combine function for numeric aggregates which don't require sumX2
3508  */
3509 Datum
3511 {
3512  NumericAggState *state1;
3513  NumericAggState *state2;
3514  MemoryContext agg_context;
3515  MemoryContext old_context;
3516 
3517  if (!AggCheckCallContext(fcinfo, &agg_context))
3518  elog(ERROR, "aggregate function called in non-aggregate context");
3519 
3520  state1 = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
3521  state2 = PG_ARGISNULL(1) ? NULL : (NumericAggState *) PG_GETARG_POINTER(1);
3522 
3523  if (state2 == NULL)
3524  PG_RETURN_POINTER(state1);
3525 
3526  /* manually copy all fields from state2 to state1 */
3527  if (state1 == NULL)
3528  {
3529  old_context = MemoryContextSwitchTo(agg_context);
3530 
3531  state1 = makeNumericAggStateCurrentContext(false);
3532  state1->N = state2->N;
3533  state1->NaNcount = state2->NaNcount;
3534  state1->maxScale = state2->maxScale;
3535  state1->maxScaleCount = state2->maxScaleCount;
3536 
3537  accum_sum_copy(&state1->sumX, &state2->sumX);
3538 
3539  MemoryContextSwitchTo(old_context);
3540 
3541  PG_RETURN_POINTER(state1);
3542  }
3543 
3544  if (state2->N > 0)
3545  {
3546  state1->N += state2->N;
3547  state1->NaNcount += state2->NaNcount;
3548 
3549  /*
3550  * These are currently only needed for moving aggregates, but let's do
3551  * the right thing anyway...
3552  */
3553  if (state2->maxScale > state1->maxScale)
3554  {
3555  state1->maxScale = state2->maxScale;
3556  state1->maxScaleCount = state2->maxScaleCount;
3557  }
3558  else if (state2->maxScale == state1->maxScale)
3559  state1->maxScaleCount += state2->maxScaleCount;
3560 
3561  /* The rest of this needs to work in the aggregate context */
3562  old_context = MemoryContextSwitchTo(agg_context);
3563 
3564  /* Accumulate sums */
3565  accum_sum_combine(&state1->sumX, &state2->sumX);
3566 
3567  MemoryContextSwitchTo(old_context);
3568  }
3569  PG_RETURN_POINTER(state1);
3570 }
3571 
3572 /*
3573  * numeric_avg_serialize
3574  * Serialize NumericAggState for numeric aggregates that don't require
3575  * sumX2.
3576  */
3577 Datum
3579 {
3582  Datum temp;
3583  bytea *sumX;
3584  bytea *result;
3585  NumericVar tmp_var;
3586 
3587  /* Ensure we disallow calling when not in aggregate context */
3588  if (!AggCheckCallContext(fcinfo, NULL))
3589  elog(ERROR, "aggregate function called in non-aggregate context");
3590 
3591  state = (NumericAggState *) PG_GETARG_POINTER(0);
3592 
3593  /*
3594  * This is a little wasteful since make_result converts the NumericVar
3595  * into a Numeric and numeric_send converts it back again. Is it worth
3596  * splitting the tasks in numeric_send into separate functions to stop
3597  * this? Doing so would also remove the fmgr call overhead.
3598  */
3599  init_var(&tmp_var);
3600  accum_sum_final(&state->sumX, &tmp_var);
3601 
3603  NumericGetDatum(make_result(&tmp_var)));
3604  sumX = DatumGetByteaPP(temp);
3605  free_var(&tmp_var);
3606 
3607  pq_begintypsend(&buf);
3608 
3609  /* N */
3610  pq_sendint64(&buf, state->N);
3611 
3612  /* sumX */
3613  pq_sendbytes(&buf, VARDATA_ANY(sumX), VARSIZE_ANY_EXHDR(sumX));
3614 
3615  /* maxScale */
3616  pq_sendint(&buf, state->maxScale, 4);
3617 
3618  /* maxScaleCount */
3619  pq_sendint64(&buf, state->maxScaleCount);
3620 
3621  /* NaNcount */
3622  pq_sendint64(&buf, state->NaNcount);
3623 
3624  result = pq_endtypsend(&buf);
3625 
3626  PG_RETURN_BYTEA_P(result);
3627 }
3628 
3629 /*
3630  * numeric_avg_deserialize
3631  * Deserialize bytea into NumericAggState for numeric aggregates that
3632  * don't require sumX2.
3633  */
3634 Datum
3636 {
3637  bytea *sstate;
3639  Datum temp;
3640  NumericVar tmp_var;
3642 
3643  if (!AggCheckCallContext(fcinfo, NULL))
3644  elog(ERROR, "aggregate function called in non-aggregate context");
3645 
3646  sstate = PG_GETARG_BYTEA_PP(0);
3647 
3648  /*
3649  * Copy the bytea into a StringInfo so that we can "receive" it using the
3650  * standard recv-function infrastructure.
3651  */
3652  initStringInfo(&buf);
3654  VARDATA_ANY(sstate), VARSIZE_ANY_EXHDR(sstate));
3655 
3656  result = makeNumericAggStateCurrentContext(false);
3657 
3658  /* N */
3659  result->N = pq_getmsgint64(&buf);
3660 
3661  /* sumX */
3663  PointerGetDatum(&buf),
3664  InvalidOid,
3665  -1);
3666  init_var_from_num(DatumGetNumeric(temp), &tmp_var);
3667  accum_sum_add(&(result->sumX), &tmp_var);
3668 
3669  /* maxScale */
3670  result->maxScale = pq_getmsgint(&buf, 4);
3671 
3672  /* maxScaleCount */
3673  result->maxScaleCount = pq_getmsgint64(&buf);
3674 
3675  /* NaNcount */
3676  result->NaNcount = pq_getmsgint64(&buf);
3677 
3678  pq_getmsgend(&buf);
3679  pfree(buf.data);
3680 
3681  PG_RETURN_POINTER(result);
3682 }
3683 
3684 /*
3685  * numeric_serialize
3686  * Serialization function for NumericAggState for numeric aggregates that
3687  * require sumX2.
3688  */
3689 Datum
3691 {
3694  Datum temp;
3695  bytea *sumX;
3696  NumericVar tmp_var;
3697  bytea *sumX2;
3698  bytea *result;
3699 
3700  /* Ensure we disallow calling when not in aggregate context */
3701  if (!AggCheckCallContext(fcinfo, NULL))
3702  elog(ERROR, "aggregate function called in non-aggregate context");
3703 
3704  state = (NumericAggState *) PG_GETARG_POINTER(0);
3705 
3706  /*
3707  * This is a little wasteful since make_result converts the NumericVar
3708  * into a Numeric and numeric_send converts it back again. Is it worth
3709  * splitting the tasks in numeric_send into separate functions to stop
3710  * this? Doing so would also remove the fmgr call overhead.
3711  */
3712  init_var(&tmp_var);
3713 
3714  accum_sum_final(&state->sumX, &tmp_var);
3716  NumericGetDatum(make_result(&tmp_var)));
3717  sumX = DatumGetByteaPP(temp);
3718 
3719  accum_sum_final(&state->sumX2, &tmp_var);
3721  NumericGetDatum(make_result(&tmp_var)));
3722  sumX2 = DatumGetByteaPP(temp);
3723 
3724  free_var(&tmp_var);
3725 
3726  pq_begintypsend(&buf);
3727 
3728  /* N */
3729  pq_sendint64(&buf, state->N);
3730 
3731  /* sumX */
3732  pq_sendbytes(&buf, VARDATA_ANY(sumX), VARSIZE_ANY_EXHDR(sumX));
3733 
3734  /* sumX2 */
3735  pq_sendbytes(&buf, VARDATA_ANY(sumX2), VARSIZE_ANY_EXHDR(sumX2));
3736 
3737  /* maxScale */
3738  pq_sendint(&buf, state->maxScale, 4);
3739 
3740  /* maxScaleCount */
3741  pq_sendint64(&buf, state->maxScaleCount);
3742 
3743  /* NaNcount */
3744  pq_sendint64(&buf, state->NaNcount);
3745 
3746  result = pq_endtypsend(&buf);
3747 
3748  PG_RETURN_BYTEA_P(result);
3749 }
3750 
3751 /*
3752  * numeric_deserialize
3753  * Deserialization function for NumericAggState for numeric aggregates that
3754  * require sumX2.
3755  */
3756 Datum
3758 {
3759  bytea *sstate;
3761  Datum temp;
3762  NumericVar sumX_var;
3763  NumericVar sumX2_var;
3765 
3766  if (!AggCheckCallContext(fcinfo, NULL))
3767  elog(ERROR, "aggregate function called in non-aggregate context");
3768 
3769  sstate = PG_GETARG_BYTEA_PP(0);
3770 
3771  /*
3772  * Copy the bytea into a StringInfo so that we can "receive" it using the
3773  * standard recv-function infrastructure.
3774  */
3775  initStringInfo(&buf);
3777  VARDATA_ANY(sstate), VARSIZE_ANY_EXHDR(sstate));
3778 
3779  result = makeNumericAggStateCurrentContext(false);
3780 
3781  /* N */
3782  result->N = pq_getmsgint64(&buf);
3783 
3784  /* sumX */
3786  PointerGetDatum(&buf),
3787  InvalidOid,
3788  -1);
3789  init_var_from_num(DatumGetNumeric(temp), &sumX_var);
3790  accum_sum_add(&(result->sumX), &sumX_var);
3791 
3792  /* sumX2 */
3794  PointerGetDatum(&buf),
3795  InvalidOid,
3796  -1);
3797  init_var_from_num(DatumGetNumeric(temp), &sumX2_var);
3798  accum_sum_add(&(result->sumX2), &sumX2_var);
3799 
3800  /* maxScale */
3801  result->maxScale = pq_getmsgint(&buf, 4);
3802 
3803  /* maxScaleCount */
3804  result->maxScaleCount = pq_getmsgint64(&buf);
3805 
3806  /* NaNcount */
3807  result->NaNcount = pq_getmsgint64(&buf);
3808 
3809  pq_getmsgend(&buf);
3810  pfree(buf.data);
3811 
3812  PG_RETURN_POINTER(result);
3813 }
3814 
3815 /*
3816  * Generic inverse transition function for numeric aggregates
3817  * (with or without requirement for X^2).
3818  */
3819 Datum
3821 {
3823 
3824  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
3825 
3826  /* Should not get here with no state */
3827  if (state == NULL)
3828  elog(ERROR, "numeric_accum_inv called with NULL state");
3829 
3830  if (!PG_ARGISNULL(1))
3831  {
3832  /* If we fail to perform the inverse transition, return NULL */
3833  if (!do_numeric_discard(state, PG_GETARG_NUMERIC(1)))
3834  PG_RETURN_NULL();
3835  }
3836 
3837  PG_RETURN_POINTER(state);
3838 }
3839 
3840 
3841 /*
3842  * Integer data types in general use Numeric accumulators to share code
3843  * and avoid risk of overflow.
3844  *
3845  * However for performance reasons optimized special-purpose accumulator
3846  * routines are used when possible.
3847  *
3848  * On platforms with 128-bit integer support, the 128-bit routines will be
3849  * used when sum(X) or sum(X*X) fit into 128-bit.
3850  *
3851  * For 16 and 32 bit inputs, the N and sum(X) fit into 64-bit so the 64-bit
3852  * accumulators will be used for SUM and AVG of these data types.
3853  */
3854 
3855 #ifdef HAVE_INT128
3856 typedef struct Int128AggState
3857 {
3858  bool calcSumX2; /* if true, calculate sumX2 */
3859  int64 N; /* count of processed numbers */
3860  int128 sumX; /* sum of processed numbers */
3861  int128 sumX2; /* sum of squares of processed numbers */
3862 } Int128AggState;
3863 
3864 /*
3865  * Prepare state data for a 128-bit aggregate function that needs to compute
3866  * sum, count and optionally sum of squares of the input.
3867  */
3868 static Int128AggState *
3869 makeInt128AggState(FunctionCallInfo fcinfo, bool calcSumX2)
3870 {
3871  Int128AggState *state;
3872  MemoryContext agg_context;
3873  MemoryContext old_context;
3874 
3875  if (!AggCheckCallContext(fcinfo, &agg_context))
3876  elog(ERROR, "aggregate function called in non-aggregate context");
3877 
3878  old_context = MemoryContextSwitchTo(agg_context);
3879 
3880  state = (Int128AggState *) palloc0(sizeof(Int128AggState));
3881  state->calcSumX2 = calcSumX2;
3882 
3883  MemoryContextSwitchTo(old_context);
3884 
3885  return state;
3886 }
3887 
3888 /*
3889  * Like makeInt128AggState(), but allocate the state in the current memory
3890  * context.
3891  */
3892 static Int128AggState *
3893 makeInt128AggStateCurrentContext(bool calcSumX2)
3894 {
3895  Int128AggState *state;
3896 
3897  state = (Int128AggState *) palloc0(sizeof(Int128AggState));
3898  state->calcSumX2 = calcSumX2;
3899 
3900  return state;
3901 }
3902 
3903 /*
3904  * Accumulate a new input value for 128-bit aggregate functions.
3905  */
3906 static void
3907 do_int128_accum(Int128AggState *state, int128 newval)
3908 {
3909  if (state->calcSumX2)
3910  state->sumX2 += newval * newval;
3911 
3912  state->sumX += newval;
3913  state->N++;
3914 }
3915 
3916 /*
3917  * Remove an input value from the aggregated state.
3918  */
3919 static void
3920 do_int128_discard(Int128AggState *state, int128 newval)
3921 {
3922  if (state->calcSumX2)
3923  state->sumX2 -= newval * newval;
3924 
3925  state->sumX -= newval;
3926  state->N--;
3927 }
3928 
3929 typedef Int128AggState PolyNumAggState;
3930 #define makePolyNumAggState makeInt128AggState
3931 #define makePolyNumAggStateCurrentContext makeInt128AggStateCurrentContext
3932 #else
3934 #define makePolyNumAggState makeNumericAggState
3935 #define makePolyNumAggStateCurrentContext makeNumericAggStateCurrentContext
3936 #endif
3937 
3938 Datum
3940 {
3941  PolyNumAggState *state;
3942 
3943  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
3944 
3945  /* Create the state data on the first call */
3946  if (state == NULL)
3947  state = makePolyNumAggState(fcinfo, true);
3948 
3949  if (!PG_ARGISNULL(1))
3950  {
3951 #ifdef HAVE_INT128
3952  do_int128_accum(state, (int128) PG_GETARG_INT16(1));
3953 #else
3954  Numeric newval;
3955 
3957  PG_GETARG_DATUM(1)));
3958  do_numeric_accum(state, newval);
3959 #endif
3960  }
3961 
3962  PG_RETURN_POINTER(state);
3963 }
3964 
3965 Datum
3967 {
3968  PolyNumAggState *state;
3969 
3970  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
3971 
3972  /* Create the state data on the first call */
3973  if (state == NULL)
3974  state = makePolyNumAggState(fcinfo, true);
3975 
3976  if (!PG_ARGISNULL(1))
3977  {
3978 #ifdef HAVE_INT128
3979  do_int128_accum(state, (int128) PG_GETARG_INT32(1));
3980 #else
3981  Numeric newval;
3982 
3984  PG_GETARG_DATUM(1)));
3985  do_numeric_accum(state, newval);
3986 #endif
3987  }
3988 
3989  PG_RETURN_POINTER(state);
3990 }
3991 
3992 Datum
3994 {
3995  NumericAggState *state;
3996 
3997  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
3998 
3999  /* Create the state data on the first call */
4000  if (state == NULL)
4001  state = makeNumericAggState(fcinfo, true);
4002 
4003  if (!PG_ARGISNULL(1))
4004  {
4005  Numeric newval;
4006 
4008  PG_GETARG_DATUM(1)));
4009  do_numeric_accum(state, newval);
4010  }
4011 
4012  PG_RETURN_POINTER(state);
4013 }
4014 
4015 /*
4016  * Combine function for numeric aggregates which require sumX2
4017  */
4018 Datum
4020 {
4021  PolyNumAggState *state1;
4022  PolyNumAggState *state2;
4023  MemoryContext agg_context;
4024  MemoryContext old_context;
4025 
4026  if (!AggCheckCallContext(fcinfo, &agg_context))
4027  elog(ERROR, "aggregate function called in non-aggregate context");
4028 
4029  state1 = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4030  state2 = PG_ARGISNULL(1) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(1);
4031 
4032  if (state2 == NULL)
4033  PG_RETURN_POINTER(state1);
4034 
4035  /* manually copy all fields from state2 to state1 */
4036  if (state1 == NULL)
4037  {
4038  old_context = MemoryContextSwitchTo(agg_context);
4039 
4040  state1 = makePolyNumAggState(fcinfo, true);
4041  state1->N = state2->N;
4042 
4043 #ifdef HAVE_INT128
4044  state1->sumX = state2->sumX;
4045  state1->sumX2 = state2->sumX2;
4046 #else
4047  accum_sum_copy(&state2->sumX, &state1->sumX);
4048  accum_sum_copy(&state2->sumX2, &state1->sumX2);
4049 #endif
4050 
4051  MemoryContextSwitchTo(old_context);
4052 
4053  PG_RETURN_POINTER(state1);
4054  }
4055 
4056  if (state2->N > 0)
4057  {
4058  state1->N += state2->N;
4059 
4060 #ifdef HAVE_INT128
4061  state1->sumX += state2->sumX;
4062  state1->sumX2 += state2->sumX2;
4063 #else
4064  /* The rest of this needs to work in the aggregate context */
4065  old_context = MemoryContextSwitchTo(agg_context);
4066 
4067  /* Accumulate sums */
4068  accum_sum_combine(&state1->sumX, &state2->sumX);
4069  accum_sum_combine(&state1->sumX2, &state2->sumX2);
4070 
4071  MemoryContextSwitchTo(old_context);
4072 #endif
4073 
4074  }
4075  PG_RETURN_POINTER(state1);
4076 }
4077 
4078 /*
4079  * numeric_poly_serialize
4080  * Serialize PolyNumAggState into bytea for aggregate functions which
4081  * require sumX2.
4082  */
4083 Datum
4085 {
4086  PolyNumAggState *state;
4088  bytea *sumX;
4089  bytea *sumX2;
4090  bytea *result;
4091 
4092  /* Ensure we disallow calling when not in aggregate context */
4093  if (!AggCheckCallContext(fcinfo, NULL))
4094  elog(ERROR, "aggregate function called in non-aggregate context");
4095 
4096  state = (PolyNumAggState *) PG_GETARG_POINTER(0);
4097 
4098  /*
4099  * If the platform supports int128 then sumX and sumX2 will be a 128 bit
4100  * integer type. Here we'll convert that into a numeric type so that the
4101  * combine state is in the same format for both int128 enabled machines
4102  * and machines which don't support that type. The logic here is that one
4103  * day we might like to send these over to another server for further
4104  * processing and we want a standard format to work with.
4105  */
4106  {
4107  Datum temp;
4108  NumericVar num;
4109 
4110  init_var(&num);
4111 
4112 #ifdef HAVE_INT128
4113  int128_to_numericvar(state->sumX, &num);
4114 #else
4115  accum_sum_final(&state->sumX, &num);
4116 #endif
4118  NumericGetDatum(make_result(&num)));
4119  sumX = DatumGetByteaPP(temp);
4120 
4121 #ifdef HAVE_INT128
4122  int128_to_numericvar(state->sumX2, &num);
4123 #else
4124  accum_sum_final(&state->sumX2, &num);
4125 #endif
4127  NumericGetDatum(make_result(&num)));
4128  sumX2 = DatumGetByteaPP(temp);
4129 
4130  free_var(&num);
4131  }
4132 
4133  pq_begintypsend(&buf);
4134 
4135  /* N */
4136  pq_sendint64(&buf, state->N);
4137 
4138  /* sumX */
4139  pq_sendbytes(&buf, VARDATA_ANY(sumX), VARSIZE_ANY_EXHDR(sumX));
4140 
4141  /* sumX2 */
4142  pq_sendbytes(&buf, VARDATA_ANY(sumX2), VARSIZE_ANY_EXHDR(sumX2));
4143 
4144  result = pq_endtypsend(&buf);
4145 
4146  PG_RETURN_BYTEA_P(result);
4147 }
4148 
4149 /*
4150  * numeric_poly_deserialize
4151  * Deserialize PolyNumAggState from bytea for aggregate functions which
4152  * require sumX2.
4153  */
4154 Datum
4156 {
4157  bytea *sstate;
4158  PolyNumAggState *result;
4159  Datum sumX;
4160  NumericVar sumX_var;
4161  Datum sumX2;
4162  NumericVar sumX2_var;
4164 
4165  if (!AggCheckCallContext(fcinfo, NULL))
4166  elog(ERROR, "aggregate function called in non-aggregate context");
4167 
4168  sstate = PG_GETARG_BYTEA_PP(0);
4169 
4170  /*
4171  * Copy the bytea into a StringInfo so that we can "receive" it using the
4172  * standard recv-function infrastructure.
4173  */
4174  initStringInfo(&buf);
4176  VARDATA_ANY(sstate), VARSIZE_ANY_EXHDR(sstate));
4177 
4178  result = makePolyNumAggStateCurrentContext(false);
4179 
4180  /* N */
4181  result->N = pq_getmsgint64(&buf);
4182 
4183  /* sumX */
4185  PointerGetDatum(&buf),
4186  InvalidOid,
4187  -1);
4188 
4189  /* sumX2 */
4191  PointerGetDatum(&buf),
4192  InvalidOid,
4193  -1);
4194 
4195  init_var_from_num(DatumGetNumeric(sumX), &sumX_var);
4196 #ifdef HAVE_INT128
4197  numericvar_to_int128(&sumX_var, &result->sumX);
4198 #else
4199  accum_sum_add(&result->sumX, &sumX_var);
4200 #endif
4201 
4202  init_var_from_num(DatumGetNumeric(sumX2), &sumX2_var);
4203 #ifdef HAVE_INT128
4204  numericvar_to_int128(&sumX2_var, &result->sumX2);
4205 #else
4206  accum_sum_add(&result->sumX2, &sumX2_var);
4207 #endif
4208 
4209  pq_getmsgend(&buf);
4210  pfree(buf.data);
4211 
4212  PG_RETURN_POINTER(result);
4213 }
4214 
4215 /*
4216  * Transition function for int8 input when we don't need sumX2.
4217  */
4218 Datum
4220 {
4221  PolyNumAggState *state;
4222 
4223  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4224 
4225  /* Create the state data on the first call */
4226  if (state == NULL)
4227  state = makePolyNumAggState(fcinfo, false);
4228 
4229  if (!PG_ARGISNULL(1))
4230  {
4231 #ifdef HAVE_INT128
4232  do_int128_accum(state, (int128) PG_GETARG_INT64(1));
4233 #else
4234  Numeric newval;
4235 
4237  PG_GETARG_DATUM(1)));
4238  do_numeric_accum(state, newval);
4239 #endif
4240  }
4241 
4242  PG_RETURN_POINTER(state);
4243 }
4244 
4245 /*
4246  * Combine function for PolyNumAggState for aggregates which don't require
4247  * sumX2
4248  */
4249 Datum
4251 {
4252  PolyNumAggState *state1;
4253  PolyNumAggState *state2;
4254  MemoryContext agg_context;
4255  MemoryContext old_context;
4256 
4257  if (!AggCheckCallContext(fcinfo, &agg_context))
4258  elog(ERROR, "aggregate function called in non-aggregate context");
4259 
4260  state1 = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4261  state2 = PG_ARGISNULL(1) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(1);
4262 
4263  if (state2 == NULL)
4264  PG_RETURN_POINTER(state1);
4265 
4266  /* manually copy all fields from state2 to state1 */
4267  if (state1 == NULL)
4268  {
4269  old_context = MemoryContextSwitchTo(agg_context);
4270 
4271  state1 = makePolyNumAggState(fcinfo, false);
4272  state1->N = state2->N;
4273 
4274 #ifdef HAVE_INT128
4275  state1->sumX = state2->sumX;
4276 #else
4277  accum_sum_copy(&state1->sumX, &state2->sumX);
4278 #endif
4279  MemoryContextSwitchTo(old_context);
4280 
4281  PG_RETURN_POINTER(state1);
4282  }
4283 
4284  if (state2->N > 0)
4285  {
4286  state1->N += state2->N;
4287 
4288 #ifdef HAVE_INT128
4289  state1->sumX += state2->sumX;
4290 #else
4291  /* The rest of this needs to work in the aggregate context */
4292  old_context = MemoryContextSwitchTo(agg_context);
4293 
4294  /* Accumulate sums */
4295  accum_sum_combine(&state1->sumX, &state2->sumX);
4296 
4297  MemoryContextSwitchTo(old_context);
4298 #endif
4299 
4300  }
4301  PG_RETURN_POINTER(state1);
4302 }
4303 
4304 /*
4305  * int8_avg_serialize
4306  * Serialize PolyNumAggState into bytea using the standard
4307  * recv-function infrastructure.
4308  */
4309 Datum
4311 {
4312  PolyNumAggState *state;
4314  bytea *sumX;
4315  bytea *result;
4316 
4317  /* Ensure we disallow calling when not in aggregate context */
4318  if (!AggCheckCallContext(fcinfo, NULL))
4319  elog(ERROR, "aggregate function called in non-aggregate context");
4320 
4321  state = (PolyNumAggState *) PG_GETARG_POINTER(0);
4322 
4323  /*
4324  * If the platform supports int128 then sumX will be a 128 integer type.
4325  * Here we'll convert that into a numeric type so that the combine state
4326  * is in the same format for both int128 enabled machines and machines
4327  * which don't support that type. The logic here is that one day we might
4328  * like to send these over to another server for further processing and we
4329  * want a standard format to work with.
4330  */
4331  {
4332  Datum temp;
4333  NumericVar num;
4334 
4335  init_var(&num);
4336 
4337 #ifdef HAVE_INT128
4338  int128_to_numericvar(state->sumX, &num);
4339 #else
4340  accum_sum_final(&state->sumX, &num);
4341 #endif
4343  NumericGetDatum(make_result(&num)));
4344  sumX = DatumGetByteaPP(temp);
4345 
4346  free_var(&num);
4347  }
4348 
4349  pq_begintypsend(&buf);
4350 
4351  /* N */
4352  pq_sendint64(&buf, state->N);
4353 
4354  /* sumX */
4355  pq_sendbytes(&buf, VARDATA_ANY(sumX), VARSIZE_ANY_EXHDR(sumX));
4356 
4357  result = pq_endtypsend(&buf);
4358 
4359  PG_RETURN_BYTEA_P(result);
4360 }
4361 
4362 /*
4363  * int8_avg_deserialize
4364  * Deserialize bytea back into PolyNumAggState.
4365  */
4366 Datum
4368 {
4369  bytea *sstate;
4370  PolyNumAggState *result;
4372  Datum temp;
4373  NumericVar num;
4374 
4375  if (!AggCheckCallContext(fcinfo, NULL))
4376  elog(ERROR, "aggregate function called in non-aggregate context");
4377 
4378  sstate = PG_GETARG_BYTEA_PP(0);
4379 
4380  /*
4381  * Copy the bytea into a StringInfo so that we can "receive" it using the
4382  * standard recv-function infrastructure.
4383  */
4384  initStringInfo(&buf);
4386  VARDATA_ANY(sstate), VARSIZE_ANY_EXHDR(sstate));
4387 
4388  result = makePolyNumAggStateCurrentContext(false);
4389 
4390  /* N */
4391  result->N = pq_getmsgint64(&buf);
4392 
4393  /* sumX */
4395  PointerGetDatum(&buf),
4396  InvalidOid,
4397  -1);
4398  init_var_from_num(DatumGetNumeric(temp), &num);
4399 #ifdef HAVE_INT128
4400  numericvar_to_int128(&num, &result->sumX);
4401 #else
4402  accum_sum_add(&result->sumX, &num);
4403 #endif
4404 
4405  pq_getmsgend(&buf);
4406  pfree(buf.data);
4407 
4408  PG_RETURN_POINTER(result);
4409 }
4410 
4411 /*
4412  * Inverse transition functions to go with the above.
4413  */
4414 
4415 Datum
4417 {
4418  PolyNumAggState *state;
4419 
4420  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4421 
4422  /* Should not get here with no state */
4423  if (state == NULL)
4424  elog(ERROR, "int2_accum_inv called with NULL state");
4425 
4426  if (!PG_ARGISNULL(1))
4427  {
4428 #ifdef HAVE_INT128
4429  do_int128_discard(state, (int128) PG_GETARG_INT16(1));
4430 #else
4431  Numeric newval;
4432 
4434  PG_GETARG_DATUM(1)));
4435 
4436  /* Should never fail, all inputs have dscale 0 */
4437  if (!do_numeric_discard(state, newval))
4438  elog(ERROR, "do_numeric_discard failed unexpectedly");
4439 #endif
4440  }
4441 
4442  PG_RETURN_POINTER(state);
4443 }
4444 
4445 Datum
4447 {
4448  PolyNumAggState *state;
4449 
4450  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4451 
4452  /* Should not get here with no state */
4453  if (state == NULL)
4454  elog(ERROR, "int4_accum_inv called with NULL state");
4455 
4456  if (!PG_ARGISNULL(1))
4457  {
4458 #ifdef HAVE_INT128
4459  do_int128_discard(state, (int128) PG_GETARG_INT32(1));
4460 #else
4461  Numeric newval;
4462 
4464  PG_GETARG_DATUM(1)));
4465 
4466  /* Should never fail, all inputs have dscale 0 */
4467  if (!do_numeric_discard(state, newval))
4468  elog(ERROR, "do_numeric_discard failed unexpectedly");
4469 #endif
4470  }
4471 
4472  PG_RETURN_POINTER(state);
4473 }
4474 
4475 Datum
4477 {
4478  NumericAggState *state;
4479 
4480  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
4481 
4482  /* Should not get here with no state */
4483  if (state == NULL)
4484  elog(ERROR, "int8_accum_inv called with NULL state");
4485 
4486  if (!PG_ARGISNULL(1))
4487  {
4488  Numeric newval;
4489 
4491  PG_GETARG_DATUM(1)));
4492 
4493  /* Should never fail, all inputs have dscale 0 */
4494  if (!do_numeric_discard(state, newval))
4495  elog(ERROR, "do_numeric_discard failed unexpectedly");
4496  }
4497 
4498  PG_RETURN_POINTER(state);
4499 }
4500 
4501 Datum
4503 {
4504  PolyNumAggState *state;
4505 
4506  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4507 
4508  /* Should not get here with no state */
4509  if (state == NULL)
4510  elog(ERROR, "int8_avg_accum_inv called with NULL state");
4511 
4512  if (!PG_ARGISNULL(1))
4513  {
4514 #ifdef HAVE_INT128
4515  do_int128_discard(state, (int128) PG_GETARG_INT64(1));
4516 #else
4517  Numeric newval;
4518 
4520  PG_GETARG_DATUM(1)));
4521 
4522  /* Should never fail, all inputs have dscale 0 */
4523  if (!do_numeric_discard(state, newval))
4524  elog(ERROR, "do_numeric_discard failed unexpectedly");
4525 #endif
4526  }
4527 
4528  PG_RETURN_POINTER(state);
4529 }
4530 
4531 Datum
4533 {
4534 #ifdef HAVE_INT128
4535  PolyNumAggState *state;
4536  Numeric res;
4538 
4539  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4540 
4541  /* If there were no non-null inputs, return NULL */
4542  if (state == NULL || state->N == 0)
4543  PG_RETURN_NULL();
4544 
4545  init_var(&result);
4546 
4547  int128_to_numericvar(state->sumX, &result);
4548 
4549  res = make_result(&result);
4550 
4551  free_var(&result);
4552 
4553  PG_RETURN_NUMERIC(res);
4554 #else
4555  return numeric_sum(fcinfo);
4556 #endif
4557 }
4558 
4559 Datum
4561 {
4562 #ifdef HAVE_INT128
4563  PolyNumAggState *state;
4565  Datum countd,
4566  sumd;
4567 
4568  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4569 
4570  /* If there were no non-null inputs, return NULL */
4571  if (state == NULL || state->N == 0)
4572  PG_RETURN_NULL();
4573 
4574  init_var(&result);
4575 
4576  int128_to_numericvar(state->sumX, &result);
4577 
4579  Int64GetDatumFast(state->N));
4580  sumd = NumericGetDatum(make_result(&result));
4581 
4582  free_var(&result);
4583 
4585 #else
4586  return numeric_avg(fcinfo);
4587 #endif
4588 }
4589 
4590 Datum
4592 {
4593  NumericAggState *state;
4594  Datum N_datum;
4595  Datum sumX_datum;
4596  NumericVar sumX_var;
4597 
4598  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
4599 
4600  /* If there were no non-null inputs, return NULL */
4601  if (state == NULL || (state->N + state->NaNcount) == 0)
4602  PG_RETURN_NULL();
4603 
4604  if (state->NaNcount > 0) /* there was at least one NaN input */
4605  PG_RETURN_NUMERIC(make_result(&const_nan));
4606 
4607  N_datum = DirectFunctionCall1(int8_numeric, Int64GetDatum(state->N));
4608 
4609  init_var(&sumX_var);
4610  accum_sum_final(&state->sumX, &sumX_var);
4611  sumX_datum = NumericGetDatum(make_result(&sumX_var));
4612  free_var(&sumX_var);
4613 
4614  PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumX_datum, N_datum));
4615 }
4616 
4617 Datum
4619 {
4620  NumericAggState *state;
4621  NumericVar sumX_var;
4622  Numeric result;
4623 
4624  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
4625 
4626  /* If there were no non-null inputs, return NULL */
4627  if (state == NULL || (state->N + state->NaNcount) == 0)
4628  PG_RETURN_NULL();
4629 
4630  if (state->NaNcount > 0) /* there was at least one NaN input */
4631  PG_RETURN_NUMERIC(make_result(&const_nan));
4632 
4633  init_var(&sumX_var);
4634  accum_sum_final(&state->sumX, &sumX_var);
4635  result = make_result(&sumX_var);
4636  free_var(&sumX_var);
4637 
4638  PG_RETURN_NUMERIC(result);
4639 }
4640 
4641 /*
4642  * Workhorse routine for the standard deviance and variance
4643  * aggregates. 'state' is aggregate's transition state.
4644  * 'variance' specifies whether we should calculate the
4645  * variance or the standard deviation. 'sample' indicates whether the
4646  * caller is interested in the sample or the population
4647  * variance/stddev.
4648  *
4649  * If appropriate variance statistic is undefined for the input,
4650  * *is_null is set to true and NULL is returned.
4651  */
4652 static Numeric
4654  bool variance, bool sample,
4655  bool *is_null)
4656 {
4657  Numeric res;
4658  NumericVar vN,
4659  vsumX,
4660  vsumX2,
4661  vNminus1;
4662  NumericVar *comp;
4663  int rscale;
4664 
4665  /* Deal with empty input and NaN-input cases */
4666  if (state == NULL || (state->N + state->NaNcount) == 0)
4667  {
4668  *is_null = true;
4669  return NULL;
4670  }
4671 
4672  *is_null = false;
4673 
4674  if (state->NaNcount > 0)
4675  return make_result(&const_nan);
4676 
4677  init_var(&vN);
4678  init_var(&vsumX);
4679  init_var(&vsumX2);
4680 
4681  int64_to_numericvar(state->N, &vN);
4682  accum_sum_final(&(state->sumX), &vsumX);
4683  accum_sum_final(&(state->sumX2), &vsumX2);
4684 
4685  /*
4686  * Sample stddev and variance are undefined when N <= 1; population stddev
4687  * is undefined when N == 0. Return NULL in either case.
4688  */
4689  if (sample)
4690  comp = &const_one;
4691  else
4692  comp = &const_zero;
4693 
4694  if (cmp_var(&vN, comp) <= 0)
4695  {
4696  *is_null = true;
4697  return NULL;
4698  }
4699 
4700  init_var(&vNminus1);
4701  sub_var(&vN, &const_one, &vNminus1);
4702 
4703  /* compute rscale for mul_var calls */
4704  rscale = vsumX.dscale * 2;
4705 
4706  mul_var(&vsumX, &vsumX, &vsumX, rscale); /* vsumX = sumX * sumX */
4707  mul_var(&vN, &vsumX2, &vsumX2, rscale); /* vsumX2 = N * sumX2 */
4708  sub_var(&vsumX2, &vsumX, &vsumX2); /* N * sumX2 - sumX * sumX */
4709 
4710  if (cmp_var(&vsumX2, &const_zero) <= 0)
4711  {
4712  /* Watch out for roundoff error producing a negative numerator */
4713  res = make_result(&const_zero);
4714  }
4715  else
4716  {
4717  if (sample)
4718  mul_var(&vN, &vNminus1, &vNminus1, 0); /* N * (N - 1) */
4719  else
4720  mul_var(&vN, &vN, &vNminus1, 0); /* N * N */
4721  rscale = select_div_scale(&vsumX2, &vNminus1);
4722  div_var(&vsumX2, &vNminus1, &vsumX, rscale, true); /* variance */
4723  if (!variance)
4724  sqrt_var(&vsumX, &vsumX, rscale); /* stddev */
4725 
4726  res = make_result(&vsumX);
4727  }
4728 
4729  free_var(&vNminus1);
4730  free_var(&vsumX);
4731  free_var(&vsumX2);
4732 
4733  return res;
4734 }
4735 
4736 Datum
4738 {
4739  NumericAggState *state;
4740  Numeric res;
4741  bool is_null;
4742 
4743  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
4744 
4745  res = numeric_stddev_internal(state, true, true, &is_null);
4746 
4747  if (is_null)
4748  PG_RETURN_NULL();
4749  else
4750  PG_RETURN_NUMERIC(res);
4751 }
4752 
4753 Datum
4755 {
4756  NumericAggState *state;
4757  Numeric res;
4758  bool is_null;
4759 
4760  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
4761 
4762  res = numeric_stddev_internal(state, false, true, &is_null);
4763 
4764  if (is_null)
4765  PG_RETURN_NULL();
4766  else
4767  PG_RETURN_NUMERIC(res);
4768 }
4769 
4770 Datum
4772 {
4773  NumericAggState *state;
4774  Numeric res;
4775  bool is_null;
4776 
4777  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
4778 
4779  res = numeric_stddev_internal(state, true, false, &is_null);
4780 
4781  if (is_null)
4782  PG_RETURN_NULL();
4783  else
4784  PG_RETURN_NUMERIC(res);
4785 }
4786 
4787 Datum
4789 {
4790  NumericAggState *state;
4791  Numeric res;
4792  bool is_null;
4793 
4794  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
4795 
4796  res = numeric_stddev_internal(state, false, false, &is_null);
4797 
4798  if (is_null)
4799  PG_RETURN_NULL();
4800  else
4801  PG_RETURN_NUMERIC(res);
4802 }
4803 
4804 #ifdef HAVE_INT128
4805 static Numeric
4806 numeric_poly_stddev_internal(Int128AggState *state,
4807  bool variance, bool sample,
4808  bool *is_null)
4809 {
4810  NumericAggState numstate;
4811  Numeric res;
4812 
4813  /* Initialize an empty agg state */
4814  memset(&numstate, 0, sizeof(NumericAggState));
4815 
4816  if (state)
4817  {
4818  NumericVar tmp_var;
4819 
4820  numstate.N = state->N;
4821 
4822  init_var(&tmp_var);
4823 
4824  int128_to_numericvar(state->sumX, &tmp_var);
4825  accum_sum_add(&numstate.sumX, &tmp_var);
4826 
4827  int128_to_numericvar(state->sumX2, &tmp_var);
4828  accum_sum_add(&numstate.sumX2, &tmp_var);
4829 
4830  free_var(&tmp_var);
4831  }
4832 
4833  res = numeric_stddev_internal(&numstate, variance, sample, is_null);
4834 
4835  if (numstate.sumX.ndigits > 0)
4836  {
4837  pfree(numstate.sumX.pos_digits);
4838  pfree(numstate.sumX.neg_digits);
4839  }
4840  if (numstate.sumX2.ndigits > 0)
4841  {
4842  pfree(numstate.sumX2.pos_digits);
4843  pfree(numstate.sumX2.neg_digits);
4844  }
4845 
4846  return res;
4847 }
4848 #endif
4849 
4850 Datum
4852 {
4853 #ifdef HAVE_INT128
4854  PolyNumAggState *state;
4855  Numeric res;
4856  bool is_null;
4857 
4858  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4859 
4860  res = numeric_poly_stddev_internal(state, true, true, &is_null);
4861 
4862  if (is_null)
4863  PG_RETURN_NULL();
4864  else
4865  PG_RETURN_NUMERIC(res);
4866 #else
4867  return numeric_var_samp(fcinfo);
4868 #endif
4869 }
4870 
4871 Datum
4873 {
4874 #ifdef HAVE_INT128
4875  PolyNumAggState *state;
4876  Numeric res;
4877  bool is_null;
4878 
4879  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4880 
4881  res = numeric_poly_stddev_internal(state, false, true, &is_null);
4882 
4883  if (is_null)
4884  PG_RETURN_NULL();
4885  else
4886  PG_RETURN_NUMERIC(res);
4887 #else
4888  return numeric_stddev_samp(fcinfo);
4889 #endif
4890 }
4891 
4892 Datum
4894 {
4895 #ifdef HAVE_INT128
4896  PolyNumAggState *state;
4897  Numeric res;
4898  bool is_null;
4899 
4900  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4901 
4902  res = numeric_poly_stddev_internal(state, true, false, &is_null);
4903 
4904  if (is_null)
4905  PG_RETURN_NULL();
4906  else
4907  PG_RETURN_NUMERIC(res);
4908 #else
4909  return numeric_var_pop(fcinfo);
4910 #endif
4911 }
4912 
4913 Datum
4915 {
4916 #ifdef HAVE_INT128
4917  PolyNumAggState *state;
4918  Numeric res;
4919  bool is_null;
4920 
4921  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4922 
4923  res = numeric_poly_stddev_internal(state, false, false, &is_null);
4924 
4925  if (is_null)
4926  PG_RETURN_NULL();
4927  else
4928  PG_RETURN_NUMERIC(res);
4929 #else
4930  return numeric_stddev_pop(fcinfo);
4931 #endif
4932 }
4933 
4934 /*
4935  * SUM transition functions for integer datatypes.
4936  *
4937  * To avoid overflow, we use accumulators wider than the input datatype.
4938  * A Numeric accumulator is needed for int8 input; for int4 and int2
4939  * inputs, we use int8 accumulators which should be sufficient for practical
4940  * purposes. (The latter two therefore don't really belong in this file,
4941  * but we keep them here anyway.)
4942  *
4943  * Because SQL defines the SUM() of no values to be NULL, not zero,
4944  * the initial condition of the transition data value needs to be NULL. This
4945  * means we can't rely on ExecAgg to automatically insert the first non-null
4946  * data value into the transition data: it doesn't know how to do the type
4947  * conversion. The upshot is that these routines have to be marked non-strict
4948  * and handle substitution of the first non-null input themselves.
4949  *
4950  * Note: these functions are used only in plain aggregation mode.
4951  * In moving-aggregate mode, we use intX_avg_accum and intX_avg_accum_inv.
4952  */
4953 
4954 Datum
4956 {
4957  int64 newval;
4958 
4959  if (PG_ARGISNULL(0))
4960  {
4961  /* No non-null input seen so far... */
4962  if (PG_ARGISNULL(1))
4963  PG_RETURN_NULL(); /* still no non-null */
4964  /* This is the first non-null input. */
4965  newval = (int64) PG_GETARG_INT16(1);
4966  PG_RETURN_INT64(newval);
4967  }
4968 
4969  /*
4970  * If we're invoked as an aggregate, we can cheat and modify our first
4971  * parameter in-place to avoid palloc overhead. If not, we need to return
4972  * the new value of the transition variable. (If int8 is pass-by-value,
4973  * then of course this is useless as well as incorrect, so just ifdef it
4974  * out.)
4975  */
4976 #ifndef USE_FLOAT8_BYVAL /* controls int8 too */
4977  if (AggCheckCallContext(fcinfo, NULL))
4978  {
4979  int64 *oldsum = (int64 *) PG_GETARG_POINTER(0);
4980 
4981  /* Leave the running sum unchanged in the new input is null */
4982  if (!PG_ARGISNULL(1))
4983  *oldsum = *oldsum + (int64) PG_GETARG_INT16(1);
4984 
4985  PG_RETURN_POINTER(oldsum);
4986  }
4987  else
4988 #endif
4989  {
4990  int64 oldsum = PG_GETARG_INT64(0);
4991 
4992  /* Leave sum unchanged if new input is null. */
4993  if (PG_ARGISNULL(1))
4994  PG_RETURN_INT64(oldsum);
4995 
4996  /* OK to do the addition. */
4997  newval = oldsum + (int64) PG_GETARG_INT16(1);
4998 
4999  PG_RETURN_INT64(newval);
5000  }
5001 }
5002 
5003 Datum
5005 {
5006  int64 newval;
5007 
5008  if (PG_ARGISNULL(0))
5009  {
5010  /* No non-null input seen so far... */
5011  if (PG_ARGISNULL(1))
5012  PG_RETURN_NULL(); /* still no non-null */
5013  /* This is the first non-null input. */
5014  newval = (int64) PG_GETARG_INT32(1);
5015  PG_RETURN_INT64(newval);
5016  }
5017 
5018  /*
5019  * If we're invoked as an aggregate, we can cheat and modify our first
5020  * parameter in-place to avoid palloc overhead. If not, we need to return
5021  * the new value of the transition variable. (If int8 is pass-by-value,
5022  * then of course this is useless as well as incorrect, so just ifdef it
5023  * out.)
5024  */
5025 #ifndef USE_FLOAT8_BYVAL /* controls int8 too */
5026  if (AggCheckCallContext(fcinfo, NULL))
5027  {
5028  int64 *oldsum = (int64 *) PG_GETARG_POINTER(0);
5029 
5030  /* Leave the running sum unchanged in the new input is null */
5031  if (!PG_ARGISNULL(1))
5032  *oldsum = *oldsum + (int64) PG_GETARG_INT32(1);
5033 
5034  PG_RETURN_POINTER(oldsum);
5035  }
5036  else
5037 #endif
5038  {
5039  int64 oldsum = PG_GETARG_INT64(0);
5040 
5041  /* Leave sum unchanged if new input is null. */
5042  if (PG_ARGISNULL(1))
5043  PG_RETURN_INT64(oldsum);
5044 
5045  /* OK to do the addition. */
5046  newval = oldsum + (int64) PG_GETARG_INT32(1);
5047 
5048  PG_RETURN_INT64(newval);
5049  }
5050 }
5051 
5052 /*
5053  * Note: this function is obsolete, it's no longer used for SUM(int8).
5054  */
5055 Datum
5057 {
5058  Numeric oldsum;
5059  Datum newval;
5060 
5061  if (PG_ARGISNULL(0))
5062  {
5063  /* No non-null input seen so far... */
5064  if (PG_ARGISNULL(1))
5065  PG_RETURN_NULL(); /* still no non-null */
5066  /* This is the first non-null input. */
5068  PG_RETURN_DATUM(newval);
5069  }
5070 
5071  /*
5072  * Note that we cannot special-case the aggregate case here, as we do for
5073  * int2_sum and int4_sum: numeric is of variable size, so we cannot modify
5074  * our first parameter in-place.
5075  */
5076 
5077  oldsum = PG_GETARG_NUMERIC(0);
5078 
5079  /* Leave sum unchanged if new input is null. */
5080  if (PG_ARGISNULL(1))
5081  PG_RETURN_NUMERIC(oldsum);
5082 
5083  /* OK to do the addition. */
5085 
5087  NumericGetDatum(oldsum), newval));
5088 }
5089 
5090 
5091 /*
5092  * Routines for avg(int2) and avg(int4). The transition datatype
5093  * is a two-element int8 array, holding count and sum.
5094  *
5095  * These functions are also used for sum(int2) and sum(int4) when
5096  * operating in moving-aggregate mode, since for correct inverse transitions
5097  * we need to count the inputs.
5098  */
5099 
5100 typedef struct Int8TransTypeData
5101 {
5102  int64 count;
5103  int64 sum;
5105 
5106 Datum
5108 {
5109  ArrayType *transarray;
5110  int16 newval = PG_GETARG_INT16(1);
5111  Int8TransTypeData *transdata;
5112 
5113  /*
5114  * If we're invoked as an aggregate, we can cheat and modify our first
5115  * parameter in-place to reduce palloc overhead. Otherwise we need to make
5116  * a copy of it before scribbling on it.
5117  */
5118  if (AggCheckCallContext(fcinfo, NULL))
5119  transarray = PG_GETARG_ARRAYTYPE_P(0);
5120  else
5121  transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
5122 
5123  if (ARR_HASNULL(transarray) ||
5124  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
5125  elog(ERROR, "expected 2-element int8 array");
5126 
5127  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
5128  transdata->count++;
5129  transdata->sum += newval;
5130 
5131  PG_RETURN_ARRAYTYPE_P(transarray);
5132 }
5133 
5134 Datum
5136 {
5137  ArrayType *transarray;
5138  int32 newval = PG_GETARG_INT32(1);
5139  Int8TransTypeData *transdata;
5140 
5141  /*
5142  * If we're invoked as an aggregate, we can cheat and modify our first
5143  * parameter in-place to reduce palloc overhead. Otherwise we need to make
5144  * a copy of it before scribbling on it.
5145  */
5146  if (AggCheckCallContext(fcinfo, NULL))
5147  transarray = PG_GETARG_ARRAYTYPE_P(0);
5148  else
5149  transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
5150 
5151  if (ARR_HASNULL(transarray) ||
5152  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
5153  elog(ERROR, "expected 2-element int8 array");
5154 
5155  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
5156  transdata->count++;
5157  transdata->sum += newval;
5158 
5159  PG_RETURN_ARRAYTYPE_P(transarray);
5160 }
5161 
5162 Datum
5164 {
5165  ArrayType *transarray1;
5166  ArrayType *transarray2;
5167  Int8TransTypeData *state1;
5168  Int8TransTypeData *state2;
5169 
5170  if (!AggCheckCallContext(fcinfo, NULL))
5171  elog(ERROR, "aggregate function called in non-aggregate context");
5172 
5173  transarray1 = PG_GETARG_ARRAYTYPE_P(0);
5174  transarray2 = PG_GETARG_ARRAYTYPE_P(1);
5175 
5176  if (ARR_HASNULL(transarray1) ||
5177  ARR_SIZE(transarray1) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
5178  elog(ERROR, "expected 2-element int8 array");
5179 
5180  if (ARR_HASNULL(transarray2) ||
5181  ARR_SIZE(transarray2) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
5182  elog(ERROR, "expected 2-element int8 array");
5183 
5184  state1 = (Int8TransTypeData *) ARR_DATA_PTR(transarray1);
5185  state2 = (Int8TransTypeData *) ARR_DATA_PTR(transarray2);
5186 
5187  state1->count += state2->count;
5188  state1->sum += state2->sum;
5189 
5190  PG_RETURN_ARRAYTYPE_P(transarray1);
5191 }
5192 
5193 Datum
5195 {
5196  ArrayType *transarray;
5197  int16 newval = PG_GETARG_INT16(1);
5198  Int8TransTypeData *transdata;
5199 
5200  /*
5201  * If we're invoked as an aggregate, we can cheat and modify our first
5202  * parameter in-place to reduce palloc overhead. Otherwise we need to make
5203  * a copy of it before scribbling on it.
5204  */
5205  if (AggCheckCallContext(fcinfo, NULL))
5206  transarray = PG_GETARG_ARRAYTYPE_P(0);
5207  else
5208  transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
5209 
5210  if (ARR_HASNULL(transarray) ||
5211  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
5212  elog(ERROR, "expected 2-element int8 array");
5213 
5214  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
5215  transdata->count--;
5216  transdata->sum -= newval;
5217 
5218  PG_RETURN_ARRAYTYPE_P(transarray);
5219 }
5220 
5221 Datum
5223 {
5224  ArrayType *transarray;
5225  int32 newval = PG_GETARG_INT32(1);
5226  Int8TransTypeData *transdata;
5227 
5228  /*
5229  * If we're invoked as an aggregate, we can cheat and modify our first
5230  * parameter in-place to reduce palloc overhead. Otherwise we need to make
5231  * a copy of it before scribbling on it.
5232  */
5233  if (AggCheckCallContext(fcinfo, NULL))
5234  transarray = PG_GETARG_ARRAYTYPE_P(0);
5235  else
5236  transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
5237 
5238  if (ARR_HASNULL(transarray) ||
5239  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
5240  elog(ERROR, "expected 2-element int8 array");
5241 
5242  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
5243  transdata->count--;
5244  transdata->sum -= newval;
5245 
5246  PG_RETURN_ARRAYTYPE_P(transarray);
5247 }
5248 
5249 Datum
5251 {
5252  ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
5253  Int8TransTypeData *transdata;
5254  Datum countd,
5255  sumd;
5256 
5257  if (ARR_HASNULL(transarray) ||
5258  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
5259  elog(ERROR, "expected 2-element int8 array");
5260  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
5261 
5262  /* SQL defines AVG of no values to be NULL */
5263  if (transdata->count == 0)
5264  PG_RETURN_NULL();
5265 
5267  Int64GetDatumFast(transdata->count));
5269  Int64GetDatumFast(transdata->sum));
5270 
5272 }
5273 
5274 /*
5275  * SUM(int2) and SUM(int4) both return int8, so we can use this
5276  * final function for both.
5277  */
5278 Datum
5280 {
5281  ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
5282  Int8TransTypeData *transdata;
5283 
5284  if (ARR_HASNULL(transarray) ||
5285  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
5286  elog(ERROR, "expected 2-element int8 array");
5287  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
5288 
5289  /* SQL defines SUM of no values to be NULL */
5290  if (transdata->count == 0)
5291  PG_RETURN_NULL();
5292 
5293  PG_RETURN_DATUM(Int64GetDatumFast(transdata->sum));
5294 }
5295 
5296 
5297 /* ----------------------------------------------------------------------
5298  *
5299  * Debug support
5300  *
5301  * ----------------------------------------------------------------------
5302  */
5303 
5304 #ifdef NUMERIC_DEBUG
5305 
5306 /*
5307  * dump_numeric() - Dump a value in the db storage format for debugging
5308  */
5309 static void
5310 dump_numeric(const char *str, Numeric num)
5311 {
5313  int ndigits;
5314  int i;
5315 
5316  ndigits = NUMERIC_NDIGITS(num);
5317 
5318  printf("%s: NUMERIC w=%d d=%d ", str,
5319  NUMERIC_WEIGHT(num), NUMERIC_DSCALE(num));
5320  switch (NUMERIC_SIGN(num))
5321  {
5322  case NUMERIC_POS:
5323  printf("POS");
5324  break;
5325  case NUMERIC_NEG:
5326  printf("NEG");
5327  break;
5328  case NUMERIC_NAN:
5329  printf("NaN");
5330  break;
5331  default:
5332  printf("SIGN=0x%x", NUMERIC_SIGN(num));
5333  break;
5334  }
5335 
5336  for (i = 0; i < ndigits; i++)
5337  printf(" %0*d", DEC_DIGITS, digits[i]);
5338  printf("\n");
5339 }
5340 
5341 
5342 /*
5343  * dump_var() - Dump a value in the variable format for debugging
5344  */
5345 static void
5346 dump_var(const char *str, NumericVar *var)
5347 {
5348  int i;
5349 
5350  printf("%s: VAR w=%d d=%d ", str, var->weight, var->dscale);
5351  switch (var->sign)
5352  {
5353  case NUMERIC_POS:
5354  printf("POS");
5355  break;
5356  case NUMERIC_NEG:
5357  printf("NEG");
5358  break;
5359  case NUMERIC_NAN:
5360  printf("NaN");
5361  break;
5362  default:
5363  printf("SIGN=0x%x", var->sign);
5364  break;
5365  }
5366 
5367  for (i = 0; i < var->ndigits; i++)
5368  printf(" %0*d", DEC_DIGITS, var->digits[i]);
5369 
5370  printf("\n");
5371 }
5372 #endif /* NUMERIC_DEBUG */
5373 
5374 
5375 /* ----------------------------------------------------------------------
5376  *
5377  * Local functions follow
5378  *
5379  * In general, these do not support NaNs --- callers must eliminate
5380  * the possibility of NaN first. (make_result() is an exception.)
5381  *
5382  * ----------------------------------------------------------------------
5383  */
5384 
5385 
5386 /*
5387  * alloc_var() -
5388  *
5389  * Allocate a digit buffer of ndigits digits (plus a spare digit for rounding)
5390  */
5391 static void
5392 alloc_var(NumericVar *var, int ndigits)
5393 {
5394  digitbuf_free(var->buf);
5395  var->buf = digitbuf_alloc(ndigits + 1);
5396  var->buf[0] = 0; /* spare digit for rounding */
5397  var->digits = var->buf + 1;
5398  var->ndigits = ndigits;
5399 }
5400 
5401 
5402 /*
5403  * free_var() -
5404  *
5405  * Return the digit buffer of a variable to the free pool
5406  */
5407 static void
5409 {
5410  digitbuf_free(var->buf);
5411  var->buf = NULL;
5412  var->digits = NULL;
5413  var->sign = NUMERIC_NAN;
5414 }
5415 
5416 
5417 /*
5418  * zero_var() -
5419  *
5420  * Set a variable to ZERO.
5421  * Note: its dscale is not touched.
5422  */
5423 static void
5425 {
5426  digitbuf_free(var->buf);
5427  var->buf = NULL;
5428  var->digits = NULL;
5429  var->ndigits = 0;
5430  var->weight = 0; /* by convention; doesn't really matter */
5431  var->sign = NUMERIC_POS; /* anything but NAN... */
5432 }
5433 
5434 
5435 /*
5436  * set_var_from_str()
5437  *
5438  * Parse a string and put the number into a variable
5439  *
5440  * This function does not handle leading or trailing spaces, and it doesn't
5441  * accept "NaN" either. It returns the end+1 position so that caller can
5442  * check for trailing spaces/garbage if deemed necessary.
5443  *
5444  * cp is the place to actually start parsing; str is what to use in error
5445  * reports. (Typically cp would be the same except advanced over spaces.)
5446  */
5447 static const char *
5448 set_var_from_str(const char *str, const char *cp, NumericVar *dest)
5449 {
5450  bool have_dp = FALSE;
5451  int i;
5452  unsigned char *decdigits;
5453  int sign = NUMERIC_POS;
5454  int dweight = -1;
5455  int ddigits;
5456  int dscale = 0;
5457  int weight;
5458  int ndigits;
5459  int offset;
5461 
5462  /*
5463  * We first parse the string to extract decimal digits and determine the
5464  * correct decimal weight. Then convert to NBASE representation.
5465  */
5466  switch (*cp)
5467  {
5468  case '+':
5469  sign = NUMERIC_POS;
5470  cp++;
5471  break;
5472 
5473  case '-':
5474  sign = NUMERIC_NEG;
5475  cp++;
5476  break;
5477  }
5478 
5479  if (*cp == '.')
5480  {
5481  have_dp = TRUE;
5482  cp++;
5483  }
5484 
5485  if (!isdigit((unsigned char) *cp))
5486  ereport(ERROR,
5487  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
5488  errmsg("invalid input syntax for type %s: \"%s\"",
5489  "numeric", str)));
5490 
5491  decdigits = (unsigned char *) palloc(strlen(cp) + DEC_DIGITS * 2);
5492 
5493  /* leading padding for digit alignment later */
5494  memset(decdigits, 0, DEC_DIGITS);
5495  i = DEC_DIGITS;
5496 
5497  while (*cp)
5498  {
5499  if (isdigit((unsigned char) *cp))
5500  {
5501  decdigits[i++] = *cp++ - '0';
5502  if (!have_dp)
5503  dweight++;
5504  else
5505  dscale++;
5506  }
5507  else if (*cp == '.')
5508  {
5509  if (have_dp)
5510  ereport(ERROR,
5511  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
5512  errmsg("invalid input syntax for type %s: \"%s\"",
5513  "numeric", str)));
5514  have_dp = TRUE;
5515  cp++;
5516  }
5517  else
5518  break;
5519  }
5520 
5521  ddigits = i - DEC_DIGITS;
5522  /* trailing padding for digit alignment later */
5523  memset(decdigits + i, 0, DEC_DIGITS - 1);
5524 
5525  /* Handle exponent, if any */
5526  if (*cp == 'e' || *cp == 'E')
5527  {
5528  long exponent;
5529  char *endptr;
5530 
5531  cp++;
5532  exponent = strtol(cp, &endptr, 10);
5533  if (endptr == cp)
5534  ereport(ERROR,
5535  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
5536  errmsg("invalid input syntax for type %s: \"%s\"",
5537  "numeric", str)));
5538  cp = endptr;
5539 
5540  /*
5541  * At this point, dweight and dscale can't be more than about
5542  * INT_MAX/2 due to the MaxAllocSize limit on string length, so
5543  * constraining the exponent similarly should be enough to prevent
5544  * integer overflow in this function. If the value is too large to
5545  * fit in storage format, make_result() will complain about it later;
5546  * for consistency use the same ereport errcode/text as make_result().
5547  */
5548  if (exponent >= INT_MAX / 2 || exponent <= -(INT_MAX / 2))
5549  ereport(ERROR,
5550  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
5551  errmsg("value overflows numeric format")));
5552  dweight += (int) exponent;
5553  dscale -= (int) exponent;
5554  if (dscale < 0)
5555  dscale = 0;
5556  }
5557 
5558  /*
5559  * Okay, convert pure-decimal representation to base NBASE. First we need
5560  * to determine the converted weight and ndigits. offset is the number of
5561  * decimal zeroes to insert before the first given digit to have a
5562  * correctly aligned first NBASE digit.
5563  */
5564  if (dweight >= 0)
5565  weight = (dweight + 1 + DEC_DIGITS - 1) / DEC_DIGITS - 1;
5566  else
5567  weight = -((-dweight - 1) / DEC_DIGITS + 1);
5568  offset = (weight + 1) * DEC_DIGITS - (dweight + 1);
5569  ndigits = (ddigits + offset + DEC_DIGITS - 1) / DEC_DIGITS;
5570 
5571  alloc_var(dest, ndigits);
5572  dest->sign = sign;
5573  dest->weight = weight;
5574  dest->dscale = dscale;
5575 
5576  i = DEC_DIGITS - offset;
5577  digits = dest->digits;
5578 
5579  while (ndigits-- > 0)
5580  {
5581 #if DEC_DIGITS == 4
5582  *digits++ = ((decdigits[i] * 10 + decdigits[i + 1]) * 10 +
5583  decdigits[i + 2]) * 10 + decdigits[i + 3];
5584 #elif DEC_DIGITS == 2
5585  *digits++ = decdigits[i] * 10 + decdigits[i + 1];
5586 #elif DEC_DIGITS == 1
5587  *digits++ = decdigits[i];
5588 #else
5589 #error unsupported NBASE
5590 #endif
5591  i += DEC_DIGITS;
5592  }
5593 
5594  pfree(decdigits);
5595 
5596  /* Strip any leading/trailing zeroes, and normalize weight if zero */
5597  strip_var(dest);
5598 
5599  /* Return end+1 position for caller */
5600  return cp;
5601 }
5602 
5603 
5604 /*
5605  * set_var_from_num() -
5606  *
5607  * Convert the packed db format into a variable
5608  */
5609 static void
5611 {
5612  int ndigits;
5613 
5614  ndigits = NUMERIC_NDIGITS(num);
5615 
5616  alloc_var(dest, ndigits);
5617 
5618  dest->weight = NUMERIC_WEIGHT(num);
5619  dest->sign = NUMERIC_SIGN(num);
5620  dest->dscale = NUMERIC_DSCALE(num);
5621 
5622  memcpy(dest->digits, NUMERIC_DIGITS(num), ndigits * sizeof(NumericDigit));
5623 }
5624 
5625 
5626 /*
5627  * init_var_from_num() -
5628  *
5629  * Initialize a variable from packed db format. The digits array is not
5630  * copied, which saves some cycles when the resulting var is not modified.
5631  * Also, there's no need to call free_var(), as long as you don't assign any
5632  * other value to it (with set_var_* functions, or by using the var as the
5633  * destination of a function like add_var())
5634  *
5635  * CAUTION: Do not modify the digits buffer of a var initialized with this
5636  * function, e.g by calling round_var() or trunc_var(), as the changes will
5637  * propagate to the original Numeric! It's OK to use it as the destination
5638  * argument of one of the calculational functions, though.
5639  */
5640 static void
5642 {
5643  dest->ndigits = NUMERIC_NDIGITS(num);
5644  dest->weight = NUMERIC_WEIGHT(num);
5645  dest->sign = NUMERIC_SIGN(num);
5646  dest->dscale = NUMERIC_DSCALE(num);
5647  dest->digits = NUMERIC_DIGITS(num);
5648  dest->buf = NULL; /* digits array is not palloc'd */
5649 }
5650 
5651 
5652 /*
5653  * set_var_from_var() -
5654  *
5655  * Copy one variable into another
5656  */
5657 static void
5659 {
5660  NumericDigit *newbuf;
5661 
5662  newbuf = digitbuf_alloc(value->ndigits + 1);
5663  newbuf[0] = 0; /* spare digit for rounding */
5664  if (value->ndigits > 0) /* else value->digits might be null */
5665  memcpy(newbuf + 1, value->digits,
5666  value->ndigits * sizeof(NumericDigit));
5667 
5668  digitbuf_free(dest->buf);
5669 
5670  memmove(dest, value, sizeof(NumericVar));
5671  dest->buf = newbuf;
5672  dest->digits = newbuf + 1;
5673 }
5674 
5675 
5676 /*
5677  * get_str_from_var() -
5678  *
5679  * Convert a var to text representation (guts of numeric_out).
5680  * The var is displayed to the number of digits indicated by its dscale.
5681  * Returns a palloc'd string.
5682  */
5683 static char *
5685 {
5686  int dscale;
5687  char *str;
5688  char *cp;
5689  char *endcp;
5690  int i;
5691  int d;
5692  NumericDigit dig;
5693 
5694 #if DEC_DIGITS > 1
5695  NumericDigit d1;
5696 #endif
5697 
5698  dscale = var->dscale;
5699 
5700  /*
5701  * Allocate space for the result.
5702  *
5703  * i is set to the # of decimal digits before decimal point. dscale is the
5704  * # of decimal digits we will print after decimal point. We may generate
5705  * as many as DEC_DIGITS-1 excess digits at the end, and in addition we
5706  * need room for sign, decimal point, null terminator.
5707  */
5708  i = (var->weight + 1) * DEC_DIGITS;
5709  if (i <= 0)
5710  i = 1;
5711 
5712  str = palloc(i + dscale + DEC_DIGITS + 2);
5713  cp = str;
5714 
5715  /*
5716  * Output a dash for negative values
5717  */
5718  if (var->sign == NUMERIC_NEG)
5719  *cp++ = '-';
5720 
5721  /*
5722  * Output all digits before the decimal point
5723  */
5724  if (var->weight < 0)
5725  {
5726  d = var->weight + 1;
5727  *cp++ = '0';
5728  }
5729  else
5730  {
5731  for (d = 0; d <= var->weight; d++)
5732  {
5733  dig = (d < var->ndigits) ? var->digits[d] : 0;
5734  /* In the first digit, suppress extra leading decimal zeroes */
5735 #if DEC_DIGITS == 4
5736  {
5737  bool putit = (d > 0);
5738 
5739  d1 = dig / 1000;
5740  dig -= d1 * 1000;
5741  putit |= (d1 > 0);
5742  if (putit)
5743  *cp++ = d1 + '0';
5744  d1 = dig / 100;
5745  dig -= d1 * 100;
5746  putit |= (d1 > 0);
5747  if (putit)
5748  *cp++ = d1 + '0';
5749  d1 = dig / 10;
5750  dig -= d1 * 10;
5751  putit |= (d1 > 0);
5752  if (putit)
5753  *cp++ = d1 + '0';
5754  *cp++ = dig + '0';
5755  }
5756 #elif DEC_DIGITS == 2
5757  d1 = dig / 10;
5758  dig -= d1 * 10;
5759  if (d1 > 0 || d > 0)
5760  *cp++ = d1 + '0';
5761  *cp++ = dig + '0';
5762 #elif DEC_DIGITS == 1
5763  *cp++ = dig + '0';
5764 #else
5765 #error unsupported NBASE
5766 #endif
5767  }
5768  }
5769 
5770  /*
5771  * If requested, output a decimal point and all the digits that follow it.
5772  * We initially put out a multiple of DEC_DIGITS digits, then truncate if
5773  * needed.
5774  */
5775  if (dscale > 0)
5776  {
5777  *cp++ = '.';
5778  endcp = cp + dscale;
5779  for (i = 0; i < dscale; d++, i += DEC_DIGITS)
5780  {
5781  dig = (d >= 0 && d < var->ndigits) ? var->digits[d] : 0;
5782 #if DEC_DIGITS == 4
5783  d1 = dig / 1000;
5784  dig -= d1 * 1000;
5785  *cp++ = d1 + '0';
5786  d1 = dig / 100;
5787  dig -= d1 * 100;
5788  *cp++ = d1 + '0';
5789  d1 = dig / 10;
5790  dig -= d1 * 10;
5791  *cp++ = d1 + '0';
5792  *cp++ = dig + '0';
5793 #elif DEC_DIGITS == 2
5794  d1 = dig / 10;
5795  dig -= d1 * 10;
5796  *cp++ = d1 + '0';
5797  *cp++ = dig + '0';
5798 #elif DEC_DIGITS == 1
5799  *cp++ = dig + '0';
5800 #else
5801 #error unsupported NBASE
5802 #endif
5803  }
5804  cp = endcp;
5805  }
5806 
5807  /*
5808  * terminate the string and return it
5809  */
5810  *cp = '\0';
5811  return str;
5812 }
5813 
5814 /*
5815  * get_str_from_var_sci() -
5816  *
5817  * Convert a var to a normalised scientific notation text representation.
5818  * This function does the heavy lifting for numeric_out_sci().
5819  *
5820  * This notation has the general form a * 10^b, where a is known as the
5821  * "significand" and b is known as the "exponent".
5822  *
5823  * Because we can't do superscript in ASCII (and because we want to copy
5824  * printf's behaviour) we display the exponent using E notation, with a
5825  * minimum of two exponent digits.
5826  *
5827  * For example, the value 1234 could be output as 1.2e+03.
5828  *
5829  * We assume that the exponent can fit into an int32.
5830  *
5831  * rscale is the number of decimal digits desired after the decimal point in
5832  * the output, negative values will be treated as meaning zero.
5833  *
5834  * Returns a palloc'd string.
5835  */
5836 static char *
5838 {
5839  int32 exponent;
5840  NumericVar denominator;
5841  NumericVar significand;
5842  int denom_scale;
5843  size_t len;
5844  char *str;
5845  char *sig_out;
5846 
5847  if (rscale < 0)
5848  rscale = 0;
5849 
5850  /*
5851  * Determine the exponent of this number in normalised form.
5852  *
5853  * This is the exponent required to represent the number with only one
5854  * significant digit before the decimal place.
5855  */
5856  if (var->ndigits > 0)
5857  {
5858  exponent = (var->weight + 1) * DEC_DIGITS;
5859 
5860  /*
5861  * Compensate for leading decimal zeroes in the first numeric digit by
5862  * decrementing the exponent.
5863  */
5864  exponent -= DEC_DIGITS - (int) log10(var->digits[0]);
5865  }
5866  else
5867  {
5868  /*
5869  * If var has no digits, then it must be zero.
5870  *
5871  * Zero doesn't technically have a meaningful exponent in normalised
5872  * notation, but we just display the exponent as zero for consistency
5873  * of output.
5874  */
5875  exponent = 0;
5876  }
5877 
5878  /*
5879  * The denominator is set to 10 raised to the power of the exponent.
5880  *
5881  * We then divide var by the denominator to get the significand, rounding
5882  * to rscale decimal digits in the process.
5883  */
5884  if (exponent < 0)
5885  denom_scale = -exponent;
5886  else
5887  denom_scale = 0;
5888 
5889  init_var(&denominator);
5890  init_var(&significand);
5891 
5892  power_var_int(&const_ten, exponent, &denominator, denom_scale);
5893  div_var(var, &denominator, &significand, rscale, true);
5894  sig_out = get_str_from_var(&significand);
5895 
5896  free_var(&denominator);
5897  free_var(&significand);
5898 
5899  /*
5900  * Allocate space f