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 {
892  FuncExpr *expr = (FuncExpr *) PG_GETARG_POINTER(0);
893  Node *ret = NULL;
894  Node *typmod;
895 
896  Assert(IsA(expr, FuncExpr));
897  Assert(list_length(expr->args) >= 2);
898 
899  typmod = (Node *) lsecond(expr->args);
900 
901  if (IsA(typmod, Const) &&!((Const *) typmod)->constisnull)
902  {
903  Node *source = (Node *) linitial(expr->args);
904  int32 old_typmod = exprTypmod(source);
905  int32 new_typmod = DatumGetInt32(((Const *) typmod)->constvalue);
906  int32 old_scale = (old_typmod - VARHDRSZ) & 0xffff;
907  int32 new_scale = (new_typmod - VARHDRSZ) & 0xffff;
908  int32 old_precision = (old_typmod - VARHDRSZ) >> 16 & 0xffff;
909  int32 new_precision = (new_typmod - VARHDRSZ) >> 16 & 0xffff;
910 
911  /*
912  * If new_typmod < VARHDRSZ, the destination is unconstrained; that's
913  * always OK. If old_typmod >= VARHDRSZ, the source is constrained,
914  * and we're OK if the scale is unchanged and the precision is not
915  * decreasing. See further notes in function header comment.
916  */
917  if (new_typmod < (int32) VARHDRSZ ||
918  (old_typmod >= (int32) VARHDRSZ &&
919  new_scale == old_scale && new_precision >= old_precision))
920  ret = relabel_to_typmod(source, new_typmod);
921  }
922 
923  PG_RETURN_POINTER(ret);
924 }
925 
926 /*
927  * numeric() -
928  *
929  * This is a special function called by the Postgres database system
930  * before a value is stored in a tuple's attribute. The precision and
931  * scale of the attribute have to be applied on the value.
932  */
933 Datum
935 {
936  Numeric num = PG_GETARG_NUMERIC(0);
937  int32 typmod = PG_GETARG_INT32(1);
938  Numeric new;
939  int32 tmp_typmod;
940  int precision;
941  int scale;
942  int ddigits;
943  int maxdigits;
944  NumericVar var;
945 
946  /*
947  * Handle NaN
948  */
949  if (NUMERIC_IS_NAN(num))
950  PG_RETURN_NUMERIC(make_result(&const_nan));
951 
952  /*
953  * If the value isn't a valid type modifier, simply return a copy of the
954  * input value
955  */
956  if (typmod < (int32) (VARHDRSZ))
957  {
958  new = (Numeric) palloc(VARSIZE(num));
959  memcpy(new, num, VARSIZE(num));
960  PG_RETURN_NUMERIC(new);
961  }
962 
963  /*
964  * Get the precision and scale out of the typmod value
965  */
966  tmp_typmod = typmod - VARHDRSZ;
967  precision = (tmp_typmod >> 16) & 0xffff;
968  scale = tmp_typmod & 0xffff;
969  maxdigits = precision - scale;
970 
971  /*
972  * If the number is certainly in bounds and due to the target scale no
973  * rounding could be necessary, just make a copy of the input and modify
974  * its scale fields, unless the larger scale forces us to abandon the
975  * short representation. (Note we assume the existing dscale is
976  * honest...)
977  */
978  ddigits = (NUMERIC_WEIGHT(num) + 1) * DEC_DIGITS;
979  if (ddigits <= maxdigits && scale >= NUMERIC_DSCALE(num)
980  && (NUMERIC_CAN_BE_SHORT(scale, NUMERIC_WEIGHT(num))
981  || !NUMERIC_IS_SHORT(num)))
982  {
983  new = (Numeric) palloc(VARSIZE(num));
984  memcpy(new, num, VARSIZE(num));
985  if (NUMERIC_IS_SHORT(num))
986  new->choice.n_short.n_header =
988  | (scale << NUMERIC_SHORT_DSCALE_SHIFT);
989  else
990  new->choice.n_long.n_sign_dscale = NUMERIC_SIGN(new) |
991  ((uint16) scale & NUMERIC_DSCALE_MASK);
992  PG_RETURN_NUMERIC(new);
993  }
994 
995  /*
996  * We really need to fiddle with things - unpack the number into a
997  * variable and let apply_typmod() do it.
998  */
999  init_var(&var);
1000 
1001  set_var_from_num(num, &var);
1002  apply_typmod(&var, typmod);
1003  new = make_result(&var);
1004 
1005  free_var(&var);
1006 
1007  PG_RETURN_NUMERIC(new);
1008 }
1009 
1010 Datum
1012 {
1014  int32 *tl;
1015  int n;
1016  int32 typmod;
1017 
1018  tl = ArrayGetIntegerTypmods(ta, &n);
1019 
1020  if (n == 2)
1021  {
1022  if (tl[0] < 1 || tl[0] > NUMERIC_MAX_PRECISION)
1023  ereport(ERROR,
1024  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1025  errmsg("NUMERIC precision %d must be between 1 and %d",
1026  tl[0], NUMERIC_MAX_PRECISION)));
1027  if (tl[1] < 0 || tl[1] > tl[0])
1028  ereport(ERROR,
1029  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1030  errmsg("NUMERIC scale %d must be between 0 and precision %d",
1031  tl[1], tl[0])));
1032  typmod = ((tl[0] << 16) | tl[1]) + VARHDRSZ;
1033  }
1034  else if (n == 1)
1035  {
1036  if (tl[0] < 1 || tl[0] > NUMERIC_MAX_PRECISION)
1037  ereport(ERROR,
1038  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1039  errmsg("NUMERIC precision %d must be between 1 and %d",
1040  tl[0], NUMERIC_MAX_PRECISION)));
1041  /* scale defaults to zero */
1042  typmod = (tl[0] << 16) + VARHDRSZ;
1043  }
1044  else
1045  {
1046  ereport(ERROR,
1047  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1048  errmsg("invalid NUMERIC type modifier")));
1049  typmod = 0; /* keep compiler quiet */
1050  }
1051 
1052  PG_RETURN_INT32(typmod);
1053 }
1054 
1055 Datum
1057 {
1058  int32 typmod = PG_GETARG_INT32(0);
1059  char *res = (char *) palloc(64);
1060 
1061  if (typmod >= 0)
1062  snprintf(res, 64, "(%d,%d)",
1063  ((typmod - VARHDRSZ) >> 16) & 0xffff,
1064  (typmod - VARHDRSZ) & 0xffff);
1065  else
1066  *res = '\0';
1067 
1068  PG_RETURN_CSTRING(res);
1069 }
1070 
1071 
1072 /* ----------------------------------------------------------------------
1073  *
1074  * Sign manipulation, rounding and the like
1075  *
1076  * ----------------------------------------------------------------------
1077  */
1078 
1079 Datum
1081 {
1082  Numeric num = PG_GETARG_NUMERIC(0);
1083  Numeric res;
1084 
1085  /*
1086  * Handle NaN
1087  */
1088  if (NUMERIC_IS_NAN(num))
1089  PG_RETURN_NUMERIC(make_result(&const_nan));
1090 
1091  /*
1092  * Do it the easy way directly on the packed format
1093  */
1094  res = (Numeric) palloc(VARSIZE(num));
1095  memcpy(res, num, VARSIZE(num));
1096 
1097  if (NUMERIC_IS_SHORT(num))
1098  res->choice.n_short.n_header =
1100  else
1102 
1103  PG_RETURN_NUMERIC(res);
1104 }
1105 
1106 
1107 Datum
1109 {
1110  Numeric num = PG_GETARG_NUMERIC(0);
1111  Numeric res;
1112 
1113  /*
1114  * Handle NaN
1115  */
1116  if (NUMERIC_IS_NAN(num))
1117  PG_RETURN_NUMERIC(make_result(&const_nan));
1118 
1119  /*
1120  * Do it the easy way directly on the packed format
1121  */
1122  res = (Numeric) palloc(VARSIZE(num));
1123  memcpy(res, num, VARSIZE(num));
1124 
1125  /*
1126  * The packed format is known to be totally zero digit trimmed always. So
1127  * we can identify a ZERO by the fact that there are no digits at all. Do
1128  * nothing to a zero.
1129  */
1130  if (NUMERIC_NDIGITS(num) != 0)
1131  {
1132  /* Else, flip the sign */
1133  if (NUMERIC_IS_SHORT(num))
1134  res->choice.n_short.n_header =
1136  else if (NUMERIC_SIGN(num) == NUMERIC_POS)
1137  res->choice.n_long.n_sign_dscale =
1138  NUMERIC_NEG | NUMERIC_DSCALE(num);
1139  else
1140  res->choice.n_long.n_sign_dscale =
1141  NUMERIC_POS | NUMERIC_DSCALE(num);
1142  }
1143 
1144  PG_RETURN_NUMERIC(res);
1145 }
1146 
1147 
1148 Datum
1150 {
1151  Numeric num = PG_GETARG_NUMERIC(0);
1152  Numeric res;
1153 
1154  res = (Numeric) palloc(VARSIZE(num));
1155  memcpy(res, num, VARSIZE(num));
1156 
1157  PG_RETURN_NUMERIC(res);
1158 }
1159 
1160 /*
1161  * numeric_sign() -
1162  *
1163  * returns -1 if the argument is less than 0, 0 if the argument is equal
1164  * to 0, and 1 if the argument is greater than zero.
1165  */
1166 Datum
1168 {
1169  Numeric num = PG_GETARG_NUMERIC(0);
1170  Numeric res;
1171  NumericVar result;
1172 
1173  /*
1174  * Handle NaN
1175  */
1176  if (NUMERIC_IS_NAN(num))
1177  PG_RETURN_NUMERIC(make_result(&const_nan));
1178 
1179  init_var(&result);
1180 
1181  /*
1182  * The packed format is known to be totally zero digit trimmed always. So
1183  * we can identify a ZERO by the fact that there are no digits at all.
1184  */
1185  if (NUMERIC_NDIGITS(num) == 0)
1186  set_var_from_var(&const_zero, &result);
1187  else
1188  {
1189  /*
1190  * And if there are some, we return a copy of ONE with the sign of our
1191  * argument
1192  */
1193  set_var_from_var(&const_one, &result);
1194  result.sign = NUMERIC_SIGN(num);
1195  }
1196 
1197  res = make_result(&result);
1198  free_var(&result);
1199 
1200  PG_RETURN_NUMERIC(res);
1201 }
1202 
1203 
1204 /*
1205  * numeric_round() -
1206  *
1207  * Round a value to have 'scale' digits after the decimal point.
1208  * We allow negative 'scale', implying rounding before the decimal
1209  * point --- Oracle interprets rounding that way.
1210  */
1211 Datum
1213 {
1214  Numeric num = PG_GETARG_NUMERIC(0);
1216  Numeric res;
1217  NumericVar arg;
1218 
1219  /*
1220  * Handle NaN
1221  */
1222  if (NUMERIC_IS_NAN(num))
1223  PG_RETURN_NUMERIC(make_result(&const_nan));
1224 
1225  /*
1226  * Limit the scale value to avoid possible overflow in calculations
1227  */
1228  scale = Max(scale, -NUMERIC_MAX_RESULT_SCALE);
1229  scale = Min(scale, NUMERIC_MAX_RESULT_SCALE);
1230 
1231  /*
1232  * Unpack the argument and round it at the proper digit position
1233  */
1234  init_var(&arg);
1235  set_var_from_num(num, &arg);
1236 
1237  round_var(&arg, scale);
1238 
1239  /* We don't allow negative output dscale */
1240  if (scale < 0)
1241  arg.dscale = 0;
1242 
1243  /*
1244  * Return the rounded result
1245  */
1246  res = make_result(&arg);
1247 
1248  free_var(&arg);
1249  PG_RETURN_NUMERIC(res);
1250 }
1251 
1252 
1253 /*
1254  * numeric_trunc() -
1255  *
1256  * Truncate a value to have 'scale' digits after the decimal point.
1257  * We allow negative 'scale', implying a truncation before the decimal
1258  * point --- Oracle interprets truncation that way.
1259  */
1260 Datum
1262 {
1263  Numeric num = PG_GETARG_NUMERIC(0);
1265  Numeric res;
1266  NumericVar arg;
1267 
1268  /*
1269  * Handle NaN
1270  */
1271  if (NUMERIC_IS_NAN(num))
1272  PG_RETURN_NUMERIC(make_result(&const_nan));
1273 
1274  /*
1275  * Limit the scale value to avoid possible overflow in calculations
1276  */
1277  scale = Max(scale, -NUMERIC_MAX_RESULT_SCALE);
1278  scale = Min(scale, NUMERIC_MAX_RESULT_SCALE);
1279 
1280  /*
1281  * Unpack the argument and truncate it at the proper digit position
1282  */
1283  init_var(&arg);
1284  set_var_from_num(num, &arg);
1285 
1286  trunc_var(&arg, scale);
1287 
1288  /* We don't allow negative output dscale */
1289  if (scale < 0)
1290  arg.dscale = 0;
1291 
1292  /*
1293  * Return the truncated result
1294  */
1295  res = make_result(&arg);
1296 
1297  free_var(&arg);
1298  PG_RETURN_NUMERIC(res);
1299 }
1300 
1301 
1302 /*
1303  * numeric_ceil() -
1304  *
1305  * Return the smallest integer greater than or equal to the argument
1306  */
1307 Datum
1309 {
1310  Numeric num = PG_GETARG_NUMERIC(0);
1311  Numeric res;
1312  NumericVar result;
1313 
1314  if (NUMERIC_IS_NAN(num))
1315  PG_RETURN_NUMERIC(make_result(&const_nan));
1316 
1317  init_var_from_num(num, &result);
1318  ceil_var(&result, &result);
1319 
1320  res = make_result(&result);
1321  free_var(&result);
1322 
1323  PG_RETURN_NUMERIC(res);
1324 }
1325 
1326 
1327 /*
1328  * numeric_floor() -
1329  *
1330  * Return the largest integer equal to or less than the argument
1331  */
1332 Datum
1334 {
1335  Numeric num = PG_GETARG_NUMERIC(0);
1336  Numeric res;
1337  NumericVar result;
1338 
1339  if (NUMERIC_IS_NAN(num))
1340  PG_RETURN_NUMERIC(make_result(&const_nan));
1341 
1342  init_var_from_num(num, &result);
1343  floor_var(&result, &result);
1344 
1345  res = make_result(&result);
1346  free_var(&result);
1347 
1348  PG_RETURN_NUMERIC(res);
1349 }
1350 
1351 
1352 /*
1353  * generate_series_numeric() -
1354  *
1355  * Generate series of numeric.
1356  */
1357 Datum
1359 {
1360  return generate_series_step_numeric(fcinfo);
1361 }
1362 
1363 Datum
1365 {
1367  FuncCallContext *funcctx;
1368  MemoryContext oldcontext;
1369 
1370  if (SRF_IS_FIRSTCALL())
1371  {
1372  Numeric start_num = PG_GETARG_NUMERIC(0);
1373  Numeric stop_num = PG_GETARG_NUMERIC(1);
1374  NumericVar steploc = const_one;
1375 
1376  /* handle NaN in start and stop values */
1377  if (NUMERIC_IS_NAN(start_num))
1378  ereport(ERROR,
1379  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1380  errmsg("start value cannot be NaN")));
1381 
1382  if (NUMERIC_IS_NAN(stop_num))
1383  ereport(ERROR,
1384  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1385  errmsg("stop value cannot be NaN")));
1386 
1387  /* see if we were given an explicit step size */
1388  if (PG_NARGS() == 3)
1389  {
1390  Numeric step_num = PG_GETARG_NUMERIC(2);
1391 
1392  if (NUMERIC_IS_NAN(step_num))
1393  ereport(ERROR,
1394  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1395  errmsg("step size cannot be NaN")));
1396 
1397  init_var_from_num(step_num, &steploc);
1398 
1399  if (cmp_var(&steploc, &const_zero) == 0)
1400  ereport(ERROR,
1401  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1402  errmsg("step size cannot equal zero")));
1403  }
1404 
1405  /* create a function context for cross-call persistence */
1406  funcctx = SRF_FIRSTCALL_INIT();
1407 
1408  /*
1409  * Switch to memory context appropriate for multiple function calls.
1410  */
1411  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1412 
1413  /* allocate memory for user context */
1414  fctx = (generate_series_numeric_fctx *)
1416 
1417  /*
1418  * Use fctx to keep state from call to call. Seed current with the
1419  * original start value. We must copy the start_num and stop_num
1420  * values rather than pointing to them, since we may have detoasted
1421  * them in the per-call context.
1422  */
1423  init_var(&fctx->current);
1424  init_var(&fctx->stop);
1425  init_var(&fctx->step);
1426 
1427  set_var_from_num(start_num, &fctx->current);
1428  set_var_from_num(stop_num, &fctx->stop);
1429  set_var_from_var(&steploc, &fctx->step);
1430 
1431  funcctx->user_fctx = fctx;
1432  MemoryContextSwitchTo(oldcontext);
1433  }
1434 
1435  /* stuff done on every call of the function */
1436  funcctx = SRF_PERCALL_SETUP();
1437 
1438  /*
1439  * Get the saved state and use current state as the result of this
1440  * iteration.
1441  */
1442  fctx = funcctx->user_fctx;
1443 
1444  if ((fctx->step.sign == NUMERIC_POS &&
1445  cmp_var(&fctx->current, &fctx->stop) <= 0) ||
1446  (fctx->step.sign == NUMERIC_NEG &&
1447  cmp_var(&fctx->current, &fctx->stop) >= 0))
1448  {
1449  Numeric result = make_result(&fctx->current);
1450 
1451  /* switch to memory context appropriate for iteration calculation */
1452  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1453 
1454  /* increment current in preparation for next iteration */
1455  add_var(&fctx->current, &fctx->step, &fctx->current);
1456  MemoryContextSwitchTo(oldcontext);
1457 
1458  /* do when there is more left to send */
1459  SRF_RETURN_NEXT(funcctx, NumericGetDatum(result));
1460  }
1461  else
1462  /* do when there is no more left */
1463  SRF_RETURN_DONE(funcctx);
1464 }
1465 
1466 
1467 /*
1468  * Implements the numeric version of the width_bucket() function
1469  * defined by SQL2003. See also width_bucket_float8().
1470  *
1471  * 'bound1' and 'bound2' are the lower and upper bounds of the
1472  * histogram's range, respectively. 'count' is the number of buckets
1473  * in the histogram. width_bucket() returns an integer indicating the
1474  * bucket number that 'operand' belongs to in an equiwidth histogram
1475  * with the specified characteristics. An operand smaller than the
1476  * lower bound is assigned to bucket 0. An operand greater than the
1477  * upper bound is assigned to an additional bucket (with number
1478  * count+1). We don't allow "NaN" for any of the numeric arguments.
1479  */
1480 Datum
1482 {
1483  Numeric operand = PG_GETARG_NUMERIC(0);
1484  Numeric bound1 = PG_GETARG_NUMERIC(1);
1485  Numeric bound2 = PG_GETARG_NUMERIC(2);
1486  int32 count = PG_GETARG_INT32(3);
1487  NumericVar count_var;
1488  NumericVar result_var;
1489  int32 result;
1490 
1491  if (count <= 0)
1492  ereport(ERROR,
1493  (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
1494  errmsg("count must be greater than zero")));
1495 
1496  if (NUMERIC_IS_NAN(operand) ||
1497  NUMERIC_IS_NAN(bound1) ||
1498  NUMERIC_IS_NAN(bound2))
1499  ereport(ERROR,
1500  (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
1501  errmsg("operand, lower bound, and upper bound cannot be NaN")));
1502 
1503  init_var(&result_var);
1504  init_var(&count_var);
1505 
1506  /* Convert 'count' to a numeric, for ease of use later */
1507  int64_to_numericvar((int64) count, &count_var);
1508 
1509  switch (cmp_numerics(bound1, bound2))
1510  {
1511  case 0:
1512  ereport(ERROR,
1513  (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
1514  errmsg("lower bound cannot equal upper bound")));
1515 
1516  /* bound1 < bound2 */
1517  case -1:
1518  if (cmp_numerics(operand, bound1) < 0)
1519  set_var_from_var(&const_zero, &result_var);
1520  else if (cmp_numerics(operand, bound2) >= 0)
1521  add_var(&count_var, &const_one, &result_var);
1522  else
1523  compute_bucket(operand, bound1, bound2,
1524  &count_var, &result_var);
1525  break;
1526 
1527  /* bound1 > bound2 */
1528  case 1:
1529  if (cmp_numerics(operand, bound1) > 0)
1530  set_var_from_var(&const_zero, &result_var);
1531  else if (cmp_numerics(operand, bound2) <= 0)
1532  add_var(&count_var, &const_one, &result_var);
1533  else
1534  compute_bucket(operand, bound1, bound2,
1535  &count_var, &result_var);
1536  break;
1537  }
1538 
1539  /* if result exceeds the range of a legal int4, we ereport here */
1540  result = numericvar_to_int32(&result_var);
1541 
1542  free_var(&count_var);
1543  free_var(&result_var);
1544 
1545  PG_RETURN_INT32(result);
1546 }
1547 
1548 /*
1549  * If 'operand' is not outside the bucket range, determine the correct
1550  * bucket for it to go. The calculations performed by this function
1551  * are derived directly from the SQL2003 spec.
1552  */
1553 static void
1554 compute_bucket(Numeric operand, Numeric bound1, Numeric bound2,
1555  NumericVar *count_var, NumericVar *result_var)
1556 {
1557  NumericVar bound1_var;
1558  NumericVar bound2_var;
1559  NumericVar operand_var;
1560 
1561  init_var_from_num(bound1, &bound1_var);
1562  init_var_from_num(bound2, &bound2_var);
1563  init_var_from_num(operand, &operand_var);
1564 
1565  if (cmp_var(&bound1_var, &bound2_var) < 0)
1566  {
1567  sub_var(&operand_var, &bound1_var, &operand_var);
1568  sub_var(&bound2_var, &bound1_var, &bound2_var);
1569  div_var(&operand_var, &bound2_var, result_var,
1570  select_div_scale(&operand_var, &bound2_var), true);
1571  }
1572  else
1573  {
1574  sub_var(&bound1_var, &operand_var, &operand_var);
1575  sub_var(&bound1_var, &bound2_var, &bound1_var);
1576  div_var(&operand_var, &bound1_var, result_var,
1577  select_div_scale(&operand_var, &bound1_var), true);
1578  }
1579 
1580  mul_var(result_var, count_var, result_var,
1581  result_var->dscale + count_var->dscale);
1582  add_var(result_var, &const_one, result_var);
1583  floor_var(result_var, result_var);
1584 
1585  free_var(&bound1_var);
1586  free_var(&bound2_var);
1587  free_var(&operand_var);
1588 }
1589 
1590 /* ----------------------------------------------------------------------
1591  *
1592  * Comparison functions
1593  *
1594  * Note: btree indexes need these routines not to leak memory; therefore,
1595  * be careful to free working copies of toasted datums. Most places don't
1596  * need to be so careful.
1597  *
1598  * Sort support:
1599  *
1600  * We implement the sortsupport strategy routine in order to get the benefit of
1601  * abbreviation. The ordinary numeric comparison can be quite slow as a result
1602  * of palloc/pfree cycles (due to detoasting packed values for alignment);
1603  * while this could be worked on itself, the abbreviation strategy gives more
1604  * speedup in many common cases.
1605  *
1606  * Two different representations are used for the abbreviated form, one in
1607  * int32 and one in int64, whichever fits into a by-value Datum. In both cases
1608  * the representation is negated relative to the original value, because we use
1609  * the largest negative value for NaN, which sorts higher than other values. We
1610  * convert the absolute value of the numeric to a 31-bit or 63-bit positive
1611  * value, and then negate it if the original number was positive.
1612  *
1613  * We abort the abbreviation process if the abbreviation cardinality is below
1614  * 0.01% of the row count (1 per 10k non-null rows). The actual break-even
1615  * point is somewhat below that, perhaps 1 per 30k (at 1 per 100k there's a
1616  * very small penalty), but we don't want to build up too many abbreviated
1617  * values before first testing for abort, so we take the slightly pessimistic
1618  * number. We make no attempt to estimate the cardinality of the real values,
1619  * since it plays no part in the cost model here (if the abbreviation is equal,
1620  * the cost of comparing equal and unequal underlying values is comparable).
1621  * We discontinue even checking for abort (saving us the hashing overhead) if
1622  * the estimated cardinality gets to 100k; that would be enough to support many
1623  * billions of rows while doing no worse than breaking even.
1624  *
1625  * ----------------------------------------------------------------------
1626  */
1627 
1628 /*
1629  * Sort support strategy routine.
1630  */
1631 Datum
1633 {
1635 
1636  ssup->comparator = numeric_fast_cmp;
1637 
1638  if (ssup->abbreviate)
1639  {
1640  NumericSortSupport *nss;
1641  MemoryContext oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
1642 
1643  nss = palloc(sizeof(NumericSortSupport));
1644 
1645  /*
1646  * palloc a buffer for handling unaligned packed values in addition to
1647  * the support struct
1648  */
1649  nss->buf = palloc(VARATT_SHORT_MAX + VARHDRSZ + 1);
1650 
1651  nss->input_count = 0;
1652  nss->estimating = true;
1653  initHyperLogLog(&nss->abbr_card, 10);
1654 
1655  ssup->ssup_extra = nss;
1656 
1657  ssup->abbrev_full_comparator = ssup->comparator;
1661 
1662  MemoryContextSwitchTo(oldcontext);
1663  }
1664 
1665  PG_RETURN_VOID();
1666 }
1667 
1668 /*
1669  * Abbreviate a numeric datum, handling NaNs and detoasting
1670  * (must not leak memory!)
1671  */
1672 static Datum
1674 {
1675  NumericSortSupport *nss = ssup->ssup_extra;
1676  void *original_varatt = PG_DETOAST_DATUM_PACKED(original_datum);
1677  Numeric value;
1678  Datum result;
1679 
1680  nss->input_count += 1;
1681 
1682  /*
1683  * This is to handle packed datums without needing a palloc/pfree cycle;
1684  * we keep and reuse a buffer large enough to handle any short datum.
1685  */
1686  if (VARATT_IS_SHORT(original_varatt))
1687  {
1688  void *buf = nss->buf;
1689  Size sz = VARSIZE_SHORT(original_varatt) - VARHDRSZ_SHORT;
1690 
1692 
1693  SET_VARSIZE(buf, VARHDRSZ + sz);
1694  memcpy(VARDATA(buf), VARDATA_SHORT(original_varatt), sz);
1695 
1696  value = (Numeric) buf;
1697  }
1698  else
1699  value = (Numeric) original_varatt;
1700 
1701  if (NUMERIC_IS_NAN(value))
1702  {
1703  result = NUMERIC_ABBREV_NAN;
1704  }
1705  else
1706  {
1707  NumericVar var;
1708 
1709  init_var_from_num(value, &var);
1710 
1711  result = numeric_abbrev_convert_var(&var, nss);
1712  }
1713 
1714  /* should happen only for external/compressed toasts */
1715  if ((Pointer) original_varatt != DatumGetPointer(original_datum))
1716  pfree(original_varatt);
1717 
1718  return result;
1719 }
1720 
1721 /*
1722  * Consider whether to abort abbreviation.
1723  *
1724  * We pay no attention to the cardinality of the non-abbreviated data. There is
1725  * no reason to do so: unlike text, we have no fast check for equal values, so
1726  * we pay the full overhead whenever the abbreviations are equal regardless of
1727  * whether the underlying values are also equal.
1728  */
1729 static bool
1730 numeric_abbrev_abort(int memtupcount, SortSupport ssup)
1731 {
1732  NumericSortSupport *nss = ssup->ssup_extra;
1733  double abbr_card;
1734 
1735  if (memtupcount < 10000 || nss->input_count < 10000 || !nss->estimating)
1736  return false;
1737 
1738  abbr_card = estimateHyperLogLog(&nss->abbr_card);
1739 
1740  /*
1741  * If we have >100k distinct values, then even if we were sorting many
1742  * billion rows we'd likely still break even, and the penalty of undoing
1743  * that many rows of abbrevs would probably not be worth it. Stop even
1744  * counting at that point.
1745  */
1746  if (abbr_card > 100000.0)
1747  {
1748 #ifdef TRACE_SORT
1749  if (trace_sort)
1750  elog(LOG,
1751  "numeric_abbrev: estimation ends at cardinality %f"
1752  " after " INT64_FORMAT " values (%d rows)",
1753  abbr_card, nss->input_count, memtupcount);
1754 #endif
1755  nss->estimating = false;
1756  return false;
1757  }
1758 
1759  /*
1760  * Target minimum cardinality is 1 per ~10k of non-null inputs. (The
1761  * break even point is somewhere between one per 100k rows, where
1762  * abbreviation has a very slight penalty, and 1 per 10k where it wins by
1763  * a measurable percentage.) We use the relatively pessimistic 10k
1764  * threshold, and add a 0.5 row fudge factor, because it allows us to
1765  * abort earlier on genuinely pathological data where we've had exactly
1766  * one abbreviated value in the first 10k (non-null) rows.
1767  */
1768  if (abbr_card < nss->input_count / 10000.0 + 0.5)
1769  {
1770 #ifdef TRACE_SORT
1771  if (trace_sort)
1772  elog(LOG,
1773  "numeric_abbrev: aborting abbreviation at cardinality %f"
1774  " below threshold %f after " INT64_FORMAT " values (%d rows)",
1775  abbr_card, nss->input_count / 10000.0 + 0.5,
1776  nss->input_count, memtupcount);
1777 #endif
1778  return true;
1779  }
1780 
1781 #ifdef TRACE_SORT
1782  if (trace_sort)
1783  elog(LOG,
1784  "numeric_abbrev: cardinality %f"
1785  " after " INT64_FORMAT " values (%d rows)",
1786  abbr_card, nss->input_count, memtupcount);
1787 #endif
1788 
1789  return false;
1790 }
1791 
1792 /*
1793  * Non-fmgr interface to the comparison routine to allow sortsupport to elide
1794  * the fmgr call. The saving here is small given how slow numeric comparisons
1795  * are, but it is a required part of the sort support API when abbreviations
1796  * are performed.
1797  *
1798  * Two palloc/pfree cycles could be saved here by using persistent buffers for
1799  * aligning short-varlena inputs, but this has not so far been considered to
1800  * be worth the effort.
1801  */
1802 static int
1804 {
1805  Numeric nx = DatumGetNumeric(x);
1806  Numeric ny = DatumGetNumeric(y);
1807  int result;
1808 
1809  result = cmp_numerics(nx, ny);
1810 
1811  if ((Pointer) nx != DatumGetPointer(x))
1812  pfree(nx);
1813  if ((Pointer) ny != DatumGetPointer(y))
1814  pfree(ny);
1815 
1816  return result;
1817 }
1818 
1819 /*
1820  * Compare abbreviations of values. (Abbreviations may be equal where the true
1821  * values differ, but if the abbreviations differ, they must reflect the
1822  * ordering of the true values.)
1823  */
1824 static int
1826 {
1827  /*
1828  * NOTE WELL: this is intentionally backwards, because the abbreviation is
1829  * negated relative to the original value, to handle NaN.
1830  */
1832  return 1;
1834  return -1;
1835  return 0;
1836 }
1837 
1838 /*
1839  * Abbreviate a NumericVar according to the available bit size.
1840  *
1841  * The 31-bit value is constructed as:
1842  *
1843  * 0 + 7bits digit weight + 24 bits digit value
1844  *
1845  * where the digit weight is in single decimal digits, not digit words, and
1846  * stored in excess-44 representation[1]. The 24-bit digit value is the 7 most
1847  * significant decimal digits of the value converted to binary. Values whose
1848  * weights would fall outside the representable range are rounded off to zero
1849  * (which is also used to represent actual zeros) or to 0x7FFFFFFF (which
1850  * otherwise cannot occur). Abbreviation therefore fails to gain any advantage
1851  * where values are outside the range 10^-44 to 10^83, which is not considered
1852  * to be a serious limitation, or when values are of the same magnitude and
1853  * equal in the first 7 decimal digits, which is considered to be an
1854  * unavoidable limitation given the available bits. (Stealing three more bits
1855  * to compare another digit would narrow the range of representable weights by
1856  * a factor of 8, which starts to look like a real limiting factor.)
1857  *
1858  * (The value 44 for the excess is essentially arbitrary)
1859  *
1860  * The 63-bit value is constructed as:
1861  *
1862  * 0 + 7bits weight + 4 x 14-bit packed digit words
1863  *
1864  * The weight in this case is again stored in excess-44, but this time it is
1865  * the original weight in digit words (i.e. powers of 10000). The first four
1866  * digit words of the value (if present; trailing zeros are assumed as needed)
1867  * are packed into 14 bits each to form the rest of the value. Again,
1868  * out-of-range values are rounded off to 0 or 0x7FFFFFFFFFFFFFFF. The
1869  * representable range in this case is 10^-176 to 10^332, which is considered
1870  * to be good enough for all practical purposes, and comparison of 4 words
1871  * means that at least 13 decimal digits are compared, which is considered to
1872  * be a reasonable compromise between effectiveness and efficiency in computing
1873  * the abbreviation.
1874  *
1875  * (The value 44 for the excess is even more arbitrary here, it was chosen just
1876  * to match the value used in the 31-bit case)
1877  *
1878  * [1] - Excess-k representation means that the value is offset by adding 'k'
1879  * and then treated as unsigned, so the smallest representable value is stored
1880  * with all bits zero. This allows simple comparisons to work on the composite
1881  * value.
1882  */
1883 
1884 #if NUMERIC_ABBREV_BITS == 64
1885 
1886 static Datum
1888 {
1889  int ndigits = var->ndigits;
1890  int weight = var->weight;
1891  int64 result;
1892 
1893  if (ndigits == 0 || weight < -44)
1894  {
1895  result = 0;
1896  }
1897  else if (weight > 83)
1898  {
1899  result = PG_INT64_MAX;
1900  }
1901  else
1902  {
1903  result = ((int64) (weight + 44) << 56);
1904 
1905  switch (ndigits)
1906  {
1907  default:
1908  result |= ((int64) var->digits[3]);
1909  /* FALLTHROUGH */
1910  case 3:
1911  result |= ((int64) var->digits[2]) << 14;
1912  /* FALLTHROUGH */
1913  case 2:
1914  result |= ((int64) var->digits[1]) << 28;
1915  /* FALLTHROUGH */
1916  case 1:
1917  result |= ((int64) var->digits[0]) << 42;
1918  break;
1919  }
1920  }
1921 
1922  /* the abbrev is negated relative to the original */
1923  if (var->sign == NUMERIC_POS)
1924  result = -result;
1925 
1926  if (nss->estimating)
1927  {
1928  uint32 tmp = ((uint32) result
1929  ^ (uint32) ((uint64) result >> 32));
1930 
1932  }
1933 
1934  return NumericAbbrevGetDatum(result);
1935 }
1936 
1937 #endif /* NUMERIC_ABBREV_BITS == 64 */
1938 
1939 #if NUMERIC_ABBREV_BITS == 32
1940 
1941 static Datum
1943 {
1944  int ndigits = var->ndigits;
1945  int weight = var->weight;
1946  int32 result;
1947 
1948  if (ndigits == 0 || weight < -11)
1949  {
1950  result = 0;
1951  }
1952  else if (weight > 20)
1953  {
1954  result = PG_INT32_MAX;
1955  }
1956  else
1957  {
1958  NumericDigit nxt1 = (ndigits > 1) ? var->digits[1] : 0;
1959 
1960  weight = (weight + 11) * 4;
1961 
1962  result = var->digits[0];
1963 
1964  /*
1965  * "result" now has 1 to 4 nonzero decimal digits. We pack in more
1966  * digits to make 7 in total (largest we can fit in 24 bits)
1967  */
1968 
1969  if (result > 999)
1970  {
1971  /* already have 4 digits, add 3 more */
1972  result = (result * 1000) + (nxt1 / 10);
1973  weight += 3;
1974  }
1975  else if (result > 99)
1976  {
1977  /* already have 3 digits, add 4 more */
1978  result = (result * 10000) + nxt1;
1979  weight += 2;
1980  }
1981  else if (result > 9)
1982  {
1983  NumericDigit nxt2 = (ndigits > 2) ? var->digits[2] : 0;
1984 
1985  /* already have 2 digits, add 5 more */
1986  result = (result * 100000) + (nxt1 * 10) + (nxt2 / 1000);
1987  weight += 1;
1988  }
1989  else
1990  {
1991  NumericDigit nxt2 = (ndigits > 2) ? var->digits[2] : 0;
1992 
1993  /* already have 1 digit, add 6 more */
1994  result = (result * 1000000) + (nxt1 * 100) + (nxt2 / 100);
1995  }
1996 
1997  result = result | (weight << 24);
1998  }
1999 
2000  /* the abbrev is negated relative to the original */
2001  if (var->sign == NUMERIC_POS)
2002  result = -result;
2003 
2004  if (nss->estimating)
2005  {
2006  uint32 tmp = (uint32) result;
2007 
2009  }
2010 
2011  return NumericAbbrevGetDatum(result);
2012 }
2013 
2014 #endif /* NUMERIC_ABBREV_BITS == 32 */
2015 
2016 /*
2017  * Ordinary (non-sortsupport) comparisons follow.
2018  */
2019 
2020 Datum
2022 {
2023  Numeric num1 = PG_GETARG_NUMERIC(0);
2024  Numeric num2 = PG_GETARG_NUMERIC(1);
2025  int result;
2026 
2027  result = cmp_numerics(num1, num2);
2028 
2029  PG_FREE_IF_COPY(num1, 0);
2030  PG_FREE_IF_COPY(num2, 1);
2031 
2032  PG_RETURN_INT32(result);
2033 }
2034 
2035 
2036 Datum
2038 {
2039  Numeric num1 = PG_GETARG_NUMERIC(0);
2040  Numeric num2 = PG_GETARG_NUMERIC(1);
2041  bool result;
2042 
2043  result = cmp_numerics(num1, num2) == 0;
2044 
2045  PG_FREE_IF_COPY(num1, 0);
2046  PG_FREE_IF_COPY(num2, 1);
2047 
2048  PG_RETURN_BOOL(result);
2049 }
2050 
2051 Datum
2053 {
2054  Numeric num1 = PG_GETARG_NUMERIC(0);
2055  Numeric num2 = PG_GETARG_NUMERIC(1);
2056  bool result;
2057 
2058  result = cmp_numerics(num1, num2) != 0;
2059 
2060  PG_FREE_IF_COPY(num1, 0);
2061  PG_FREE_IF_COPY(num2, 1);
2062 
2063  PG_RETURN_BOOL(result);
2064 }
2065 
2066 Datum
2068 {
2069  Numeric num1 = PG_GETARG_NUMERIC(0);
2070  Numeric num2 = PG_GETARG_NUMERIC(1);
2071  bool result;
2072 
2073  result = cmp_numerics(num1, num2) > 0;
2074 
2075  PG_FREE_IF_COPY(num1, 0);
2076  PG_FREE_IF_COPY(num2, 1);
2077 
2078  PG_RETURN_BOOL(result);
2079 }
2080 
2081 Datum
2083 {
2084  Numeric num1 = PG_GETARG_NUMERIC(0);
2085  Numeric num2 = PG_GETARG_NUMERIC(1);
2086  bool result;
2087 
2088  result = cmp_numerics(num1, num2) >= 0;
2089 
2090  PG_FREE_IF_COPY(num1, 0);
2091  PG_FREE_IF_COPY(num2, 1);
2092 
2093  PG_RETURN_BOOL(result);
2094 }
2095 
2096 Datum
2098 {
2099  Numeric num1 = PG_GETARG_NUMERIC(0);
2100  Numeric num2 = PG_GETARG_NUMERIC(1);
2101  bool result;
2102 
2103  result = cmp_numerics(num1, num2) < 0;
2104 
2105  PG_FREE_IF_COPY(num1, 0);
2106  PG_FREE_IF_COPY(num2, 1);
2107 
2108  PG_RETURN_BOOL(result);
2109 }
2110 
2111 Datum
2113 {
2114  Numeric num1 = PG_GETARG_NUMERIC(0);
2115  Numeric num2 = PG_GETARG_NUMERIC(1);
2116  bool result;
2117 
2118  result = cmp_numerics(num1, num2) <= 0;
2119 
2120  PG_FREE_IF_COPY(num1, 0);
2121  PG_FREE_IF_COPY(num2, 1);
2122 
2123  PG_RETURN_BOOL(result);
2124 }
2125 
2126 static int
2128 {
2129  int result;
2130 
2131  /*
2132  * We consider all NANs to be equal and larger than any non-NAN. This is
2133  * somewhat arbitrary; the important thing is to have a consistent sort
2134  * order.
2135  */
2136  if (NUMERIC_IS_NAN(num1))
2137  {
2138  if (NUMERIC_IS_NAN(num2))
2139  result = 0; /* NAN = NAN */
2140  else
2141  result = 1; /* NAN > non-NAN */
2142  }
2143  else if (NUMERIC_IS_NAN(num2))
2144  {
2145  result = -1; /* non-NAN < NAN */
2146  }
2147  else
2148  {
2149  result = cmp_var_common(NUMERIC_DIGITS(num1), NUMERIC_NDIGITS(num1),
2150  NUMERIC_WEIGHT(num1), NUMERIC_SIGN(num1),
2151  NUMERIC_DIGITS(num2), NUMERIC_NDIGITS(num2),
2152  NUMERIC_WEIGHT(num2), NUMERIC_SIGN(num2));
2153  }
2154 
2155  return result;
2156 }
2157 
2158 Datum
2160 {
2161  Numeric key = PG_GETARG_NUMERIC(0);
2162  Datum digit_hash;
2163  Datum result;
2164  int weight;
2165  int start_offset;
2166  int end_offset;
2167  int i;
2168  int hash_len;
2170 
2171  /* If it's NaN, don't try to hash the rest of the fields */
2172  if (NUMERIC_IS_NAN(key))
2173  PG_RETURN_UINT32(0);
2174 
2175  weight = NUMERIC_WEIGHT(key);
2176  start_offset = 0;
2177  end_offset = 0;
2178 
2179  /*
2180  * Omit any leading or trailing zeros from the input to the hash. The
2181  * numeric implementation *should* guarantee that leading and trailing
2182  * zeros are suppressed, but we're paranoid. Note that we measure the
2183  * starting and ending offsets in units of NumericDigits, not bytes.
2184  */
2185  digits = NUMERIC_DIGITS(key);
2186  for (i = 0; i < NUMERIC_NDIGITS(key); i++)
2187  {
2188  if (digits[i] != (NumericDigit) 0)
2189  break;
2190 
2191  start_offset++;
2192 
2193  /*
2194  * The weight is effectively the # of digits before the decimal point,
2195  * so decrement it for each leading zero we skip.
2196  */
2197  weight--;
2198  }
2199 
2200  /*
2201  * If there are no non-zero digits, then the value of the number is zero,
2202  * regardless of any other fields.
2203  */
2204  if (NUMERIC_NDIGITS(key) == start_offset)
2205  PG_RETURN_UINT32(-1);
2206 
2207  for (i = NUMERIC_NDIGITS(key) - 1; i >= 0; i--)
2208  {
2209  if (digits[i] != (NumericDigit) 0)
2210  break;
2211 
2212  end_offset++;
2213  }
2214 
2215  /* If we get here, there should be at least one non-zero digit */
2216  Assert(start_offset + end_offset < NUMERIC_NDIGITS(key));
2217 
2218  /*
2219  * Note that we don't hash on the Numeric's scale, since two numerics can
2220  * compare equal but have different scales. We also don't hash on the
2221  * sign, although we could: since a sign difference implies inequality,
2222  * this shouldn't affect correctness.
2223  */
2224  hash_len = NUMERIC_NDIGITS(key) - start_offset - end_offset;
2225  digit_hash = hash_any((unsigned char *) (NUMERIC_DIGITS(key) + start_offset),
2226  hash_len * sizeof(NumericDigit));
2227 
2228  /* Mix in the weight, via XOR */
2229  result = digit_hash ^ weight;
2230 
2231  PG_RETURN_DATUM(result);
2232 }
2233 
2234 
2235 /* ----------------------------------------------------------------------
2236  *
2237  * Basic arithmetic functions
2238  *
2239  * ----------------------------------------------------------------------
2240  */
2241 
2242 
2243 /*
2244  * numeric_add() -
2245  *
2246  * Add two numerics
2247  */
2248 Datum
2250 {
2251  Numeric num1 = PG_GETARG_NUMERIC(0);
2252  Numeric num2 = PG_GETARG_NUMERIC(1);
2253  NumericVar arg1;
2254  NumericVar arg2;
2255  NumericVar result;
2256  Numeric res;
2257 
2258  /*
2259  * Handle NaN
2260  */
2261  if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2262  PG_RETURN_NUMERIC(make_result(&const_nan));
2263 
2264  /*
2265  * Unpack the values, let add_var() compute the result and return it.
2266  */
2267  init_var_from_num(num1, &arg1);
2268  init_var_from_num(num2, &arg2);
2269 
2270  init_var(&result);
2271  add_var(&arg1, &arg2, &result);
2272 
2273  res = make_result(&result);
2274 
2275  free_var(&result);
2276 
2277  PG_RETURN_NUMERIC(res);
2278 }
2279 
2280 
2281 /*
2282  * numeric_sub() -
2283  *
2284  * Subtract one numeric from another
2285  */
2286 Datum
2288 {
2289  Numeric num1 = PG_GETARG_NUMERIC(0);
2290  Numeric num2 = PG_GETARG_NUMERIC(1);
2291  NumericVar arg1;
2292  NumericVar arg2;
2293  NumericVar result;
2294  Numeric res;
2295 
2296  /*
2297  * Handle NaN
2298  */
2299  if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2300  PG_RETURN_NUMERIC(make_result(&const_nan));
2301 
2302  /*
2303  * Unpack the values, let sub_var() compute the result and return it.
2304  */
2305  init_var_from_num(num1, &arg1);
2306  init_var_from_num(num2, &arg2);
2307 
2308  init_var(&result);
2309  sub_var(&arg1, &arg2, &result);
2310 
2311  res = make_result(&result);
2312 
2313  free_var(&result);
2314 
2315  PG_RETURN_NUMERIC(res);
2316 }
2317 
2318 
2319 /*
2320  * numeric_mul() -
2321  *
2322  * Calculate the product of two numerics
2323  */
2324 Datum
2326 {
2327  Numeric num1 = PG_GETARG_NUMERIC(0);
2328  Numeric num2 = PG_GETARG_NUMERIC(1);
2329  NumericVar arg1;
2330  NumericVar arg2;
2331  NumericVar result;
2332  Numeric res;
2333 
2334  /*
2335  * Handle NaN
2336  */
2337  if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2338  PG_RETURN_NUMERIC(make_result(&const_nan));
2339 
2340  /*
2341  * Unpack the values, let mul_var() compute the result and return it.
2342  * Unlike add_var() and sub_var(), mul_var() will round its result. In the
2343  * case of numeric_mul(), which is invoked for the * operator on numerics,
2344  * we request exact representation for the product (rscale = sum(dscale of
2345  * arg1, dscale of arg2)).
2346  */
2347  init_var_from_num(num1, &arg1);
2348  init_var_from_num(num2, &arg2);
2349 
2350  init_var(&result);
2351  mul_var(&arg1, &arg2, &result, arg1.dscale + arg2.dscale);
2352 
2353  res = make_result(&result);
2354 
2355  free_var(&result);
2356 
2357  PG_RETURN_NUMERIC(res);
2358 }
2359 
2360 
2361 /*
2362  * numeric_div() -
2363  *
2364  * Divide one numeric into another
2365  */
2366 Datum
2368 {
2369  Numeric num1 = PG_GETARG_NUMERIC(0);
2370  Numeric num2 = PG_GETARG_NUMERIC(1);
2371  NumericVar arg1;
2372  NumericVar arg2;
2373  NumericVar result;
2374  Numeric res;
2375  int rscale;
2376 
2377  /*
2378  * Handle NaN
2379  */
2380  if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2381  PG_RETURN_NUMERIC(make_result(&const_nan));
2382 
2383  /*
2384  * Unpack the arguments
2385  */
2386  init_var_from_num(num1, &arg1);
2387  init_var_from_num(num2, &arg2);
2388 
2389  init_var(&result);
2390 
2391  /*
2392  * Select scale for division result
2393  */
2394  rscale = select_div_scale(&arg1, &arg2);
2395 
2396  /*
2397  * Do the divide and return the result
2398  */
2399  div_var(&arg1, &arg2, &result, rscale, true);
2400 
2401  res = make_result(&result);
2402 
2403  free_var(&result);
2404 
2405  PG_RETURN_NUMERIC(res);
2406 }
2407 
2408 
2409 /*
2410  * numeric_div_trunc() -
2411  *
2412  * Divide one numeric into another, truncating the result to an integer
2413  */
2414 Datum
2416 {
2417  Numeric num1 = PG_GETARG_NUMERIC(0);
2418  Numeric num2 = PG_GETARG_NUMERIC(1);
2419  NumericVar arg1;
2420  NumericVar arg2;
2421  NumericVar result;
2422  Numeric res;
2423 
2424  /*
2425  * Handle NaN
2426  */
2427  if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2428  PG_RETURN_NUMERIC(make_result(&const_nan));
2429 
2430  /*
2431  * Unpack the arguments
2432  */
2433  init_var_from_num(num1, &arg1);
2434  init_var_from_num(num2, &arg2);
2435 
2436  init_var(&result);
2437 
2438  /*
2439  * Do the divide and return the result
2440  */
2441  div_var(&arg1, &arg2, &result, 0, false);
2442 
2443  res = make_result(&result);
2444 
2445  free_var(&result);
2446 
2447  PG_RETURN_NUMERIC(res);
2448 }
2449 
2450 
2451 /*
2452  * numeric_mod() -
2453  *
2454  * Calculate the modulo of two numerics
2455  */
2456 Datum
2458 {
2459  Numeric num1 = PG_GETARG_NUMERIC(0);
2460  Numeric num2 = PG_GETARG_NUMERIC(1);
2461  Numeric res;
2462  NumericVar arg1;
2463  NumericVar arg2;
2464  NumericVar result;
2465 
2466  if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2467  PG_RETURN_NUMERIC(make_result(&const_nan));
2468 
2469  init_var_from_num(num1, &arg1);
2470  init_var_from_num(num2, &arg2);
2471 
2472  init_var(&result);
2473 
2474  mod_var(&arg1, &arg2, &result);
2475 
2476  res = make_result(&result);
2477 
2478  free_var(&result);
2479 
2480  PG_RETURN_NUMERIC(res);
2481 }
2482 
2483 
2484 /*
2485  * numeric_inc() -
2486  *
2487  * Increment a number by one
2488  */
2489 Datum
2491 {
2492  Numeric num = PG_GETARG_NUMERIC(0);
2493  NumericVar arg;
2494  Numeric res;
2495 
2496  /*
2497  * Handle NaN
2498  */
2499  if (NUMERIC_IS_NAN(num))
2500  PG_RETURN_NUMERIC(make_result(&const_nan));
2501 
2502  /*
2503  * Compute the result and return it
2504  */
2505  init_var_from_num(num, &arg);
2506 
2507  add_var(&arg, &const_one, &arg);
2508 
2509  res = make_result(&arg);
2510 
2511  free_var(&arg);
2512 
2513  PG_RETURN_NUMERIC(res);
2514 }
2515 
2516 
2517 /*
2518  * numeric_smaller() -
2519  *
2520  * Return the smaller of two numbers
2521  */
2522 Datum
2524 {
2525  Numeric num1 = PG_GETARG_NUMERIC(0);
2526  Numeric num2 = PG_GETARG_NUMERIC(1);
2527 
2528  /*
2529  * Use cmp_numerics so that this will agree with the comparison operators,
2530  * particularly as regards comparisons involving NaN.
2531  */
2532  if (cmp_numerics(num1, num2) < 0)
2533  PG_RETURN_NUMERIC(num1);
2534  else
2535  PG_RETURN_NUMERIC(num2);
2536 }
2537 
2538 
2539 /*
2540  * numeric_larger() -
2541  *
2542  * Return the larger of two numbers
2543  */
2544 Datum
2546 {
2547  Numeric num1 = PG_GETARG_NUMERIC(0);
2548  Numeric num2 = PG_GETARG_NUMERIC(1);
2549 
2550  /*
2551  * Use cmp_numerics so that this will agree with the comparison operators,
2552  * particularly as regards comparisons involving NaN.
2553  */
2554  if (cmp_numerics(num1, num2) > 0)
2555  PG_RETURN_NUMERIC(num1);
2556  else
2557  PG_RETURN_NUMERIC(num2);
2558 }
2559 
2560 
2561 /* ----------------------------------------------------------------------
2562  *
2563  * Advanced math functions
2564  *
2565  * ----------------------------------------------------------------------
2566  */
2567 
2568 /*
2569  * numeric_fac()
2570  *
2571  * Compute factorial
2572  */
2573 Datum
2575 {
2576  int64 num = PG_GETARG_INT64(0);
2577  Numeric res;
2578  NumericVar fact;
2579  NumericVar result;
2580 
2581  if (num <= 1)
2582  {
2583  res = make_result(&const_one);
2584  PG_RETURN_NUMERIC(res);
2585  }
2586  /* Fail immediately if the result would overflow */
2587  if (num > 32177)
2588  ereport(ERROR,
2589  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
2590  errmsg("value overflows numeric format")));
2591 
2592  init_var(&fact);
2593  init_var(&result);
2594 
2595  int64_to_numericvar(num, &result);
2596 
2597  for (num = num - 1; num > 1; num--)
2598  {
2599  /* this loop can take awhile, so allow it to be interrupted */
2601 
2602  int64_to_numericvar(num, &fact);
2603 
2604  mul_var(&result, &fact, &result, 0);
2605  }
2606 
2607  res = make_result(&result);
2608 
2609  free_var(&fact);
2610  free_var(&result);
2611 
2612  PG_RETURN_NUMERIC(res);
2613 }
2614 
2615 
2616 /*
2617  * numeric_sqrt() -
2618  *
2619  * Compute the square root of a numeric.
2620  */
2621 Datum
2623 {
2624  Numeric num = PG_GETARG_NUMERIC(0);
2625  Numeric res;
2626  NumericVar arg;
2627  NumericVar result;
2628  int sweight;
2629  int rscale;
2630 
2631  /*
2632  * Handle NaN
2633  */
2634  if (NUMERIC_IS_NAN(num))
2635  PG_RETURN_NUMERIC(make_result(&const_nan));
2636 
2637  /*
2638  * Unpack the argument and determine the result scale. We choose a scale
2639  * to give at least NUMERIC_MIN_SIG_DIGITS significant digits; but in any
2640  * case not less than the input's dscale.
2641  */
2642  init_var_from_num(num, &arg);
2643 
2644  init_var(&result);
2645 
2646  /* Assume the input was normalized, so arg.weight is accurate */
2647  sweight = (arg.weight + 1) * DEC_DIGITS / 2 - 1;
2648 
2649  rscale = NUMERIC_MIN_SIG_DIGITS - sweight;
2650  rscale = Max(rscale, arg.dscale);
2651  rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
2652  rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
2653 
2654  /*
2655  * Let sqrt_var() do the calculation and return the result.
2656  */
2657  sqrt_var(&arg, &result, rscale);
2658 
2659  res = make_result(&result);
2660 
2661  free_var(&result);
2662 
2663  PG_RETURN_NUMERIC(res);
2664 }
2665 
2666 
2667 /*
2668  * numeric_exp() -
2669  *
2670  * Raise e to the power of x
2671  */
2672 Datum
2674 {
2675  Numeric num = PG_GETARG_NUMERIC(0);
2676  Numeric res;
2677  NumericVar arg;
2678  NumericVar result;
2679  int rscale;
2680  double val;
2681 
2682  /*
2683  * Handle NaN
2684  */
2685  if (NUMERIC_IS_NAN(num))
2686  PG_RETURN_NUMERIC(make_result(&const_nan));
2687 
2688  /*
2689  * Unpack the argument and determine the result scale. We choose a scale
2690  * to give at least NUMERIC_MIN_SIG_DIGITS significant digits; but in any
2691  * case not less than the input's dscale.
2692  */
2693  init_var_from_num(num, &arg);
2694 
2695  init_var(&result);
2696 
2697  /* convert input to float8, ignoring overflow */
2699 
2700  /*
2701  * log10(result) = num * log10(e), so this is approximately the decimal
2702  * weight of the result:
2703  */
2704  val *= 0.434294481903252;
2705 
2706  /* limit to something that won't cause integer overflow */
2707  val = Max(val, -NUMERIC_MAX_RESULT_SCALE);
2708  val = Min(val, NUMERIC_MAX_RESULT_SCALE);
2709 
2710  rscale = NUMERIC_MIN_SIG_DIGITS - (int) val;
2711  rscale = Max(rscale, arg.dscale);
2712  rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
2713  rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
2714 
2715  /*
2716  * Let exp_var() do the calculation and return the result.
2717  */
2718  exp_var(&arg, &result, rscale);
2719 
2720  res = make_result(&result);
2721 
2722  free_var(&result);
2723 
2724  PG_RETURN_NUMERIC(res);
2725 }
2726 
2727 
2728 /*
2729  * numeric_ln() -
2730  *
2731  * Compute the natural logarithm of x
2732  */
2733 Datum
2735 {
2736  Numeric num = PG_GETARG_NUMERIC(0);
2737  Numeric res;
2738  NumericVar arg;
2739  NumericVar result;
2740  int ln_dweight;
2741  int rscale;
2742 
2743  /*
2744  * Handle NaN
2745  */
2746  if (NUMERIC_IS_NAN(num))
2747  PG_RETURN_NUMERIC(make_result(&const_nan));
2748 
2749  init_var_from_num(num, &arg);
2750  init_var(&result);
2751 
2752  /* Estimated dweight of logarithm */
2753  ln_dweight = estimate_ln_dweight(&arg);
2754 
2755  rscale = NUMERIC_MIN_SIG_DIGITS - ln_dweight;
2756  rscale = Max(rscale, arg.dscale);
2757  rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
2758  rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
2759 
2760  ln_var(&arg, &result, rscale);
2761 
2762  res = make_result(&result);
2763 
2764  free_var(&result);
2765 
2766  PG_RETURN_NUMERIC(res);
2767 }
2768 
2769 
2770 /*
2771  * numeric_log() -
2772  *
2773  * Compute the logarithm of x in a given base
2774  */
2775 Datum
2777 {
2778  Numeric num1 = PG_GETARG_NUMERIC(0);
2779  Numeric num2 = PG_GETARG_NUMERIC(1);
2780  Numeric res;
2781  NumericVar arg1;
2782  NumericVar arg2;
2783  NumericVar result;
2784 
2785  /*
2786  * Handle NaN
2787  */
2788  if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2789  PG_RETURN_NUMERIC(make_result(&const_nan));
2790 
2791  /*
2792  * Initialize things
2793  */
2794  init_var_from_num(num1, &arg1);
2795  init_var_from_num(num2, &arg2);
2796  init_var(&result);
2797 
2798  /*
2799  * Call log_var() to compute and return the result; note it handles scale
2800  * selection itself.
2801  */
2802  log_var(&arg1, &arg2, &result);
2803 
2804  res = make_result(&result);
2805 
2806  free_var(&result);
2807 
2808  PG_RETURN_NUMERIC(res);
2809 }
2810 
2811 
2812 /*
2813  * numeric_power() -
2814  *
2815  * Raise b to the power of x
2816  */
2817 Datum
2819 {
2820  Numeric num1 = PG_GETARG_NUMERIC(0);
2821  Numeric num2 = PG_GETARG_NUMERIC(1);
2822  Numeric res;
2823  NumericVar arg1;
2824  NumericVar arg2;
2825  NumericVar arg2_trunc;
2826  NumericVar result;
2827 
2828  /*
2829  * Handle NaN
2830  */
2831  if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2832  PG_RETURN_NUMERIC(make_result(&const_nan));
2833 
2834  /*
2835  * Initialize things
2836  */
2837  init_var(&arg2_trunc);
2838  init_var(&result);
2839  init_var_from_num(num1, &arg1);
2840  init_var_from_num(num2, &arg2);
2841 
2842  set_var_from_var(&arg2, &arg2_trunc);
2843  trunc_var(&arg2_trunc, 0);
2844 
2845  /*
2846  * The SQL spec requires that we emit a particular SQLSTATE error code for
2847  * certain error conditions. Specifically, we don't return a
2848  * divide-by-zero error code for 0 ^ -1.
2849  */
2850  if (cmp_var(&arg1, &const_zero) == 0 &&
2851  cmp_var(&arg2, &const_zero) < 0)
2852  ereport(ERROR,
2853  (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
2854  errmsg("zero raised to a negative power is undefined")));
2855 
2856  if (cmp_var(&arg1, &const_zero) < 0 &&
2857  cmp_var(&arg2, &arg2_trunc) != 0)
2858  ereport(ERROR,
2859  (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
2860  errmsg("a negative number raised to a non-integer power yields a complex result")));
2861 
2862  /*
2863  * Call power_var() to compute and return the result; note it handles
2864  * scale selection itself.
2865  */
2866  power_var(&arg1, &arg2, &result);
2867 
2868  res = make_result(&result);
2869 
2870  free_var(&result);
2871  free_var(&arg2_trunc);
2872 
2873  PG_RETURN_NUMERIC(res);
2874 }
2875 
2876 /*
2877  * numeric_scale() -
2878  *
2879  * Returns the scale, i.e. the count of decimal digits in the fractional part
2880  */
2881 Datum
2883 {
2884  Numeric num = PG_GETARG_NUMERIC(0);
2885 
2886  if (NUMERIC_IS_NAN(num))
2887  PG_RETURN_NULL();
2888 
2890 }
2891 
2892 
2893 
2894 /* ----------------------------------------------------------------------
2895  *
2896  * Type conversion functions
2897  *
2898  * ----------------------------------------------------------------------
2899  */
2900 
2901 
2902 Datum
2904 {
2905  int32 val = PG_GETARG_INT32(0);
2906  Numeric res;
2907  NumericVar result;
2908 
2909  init_var(&result);
2910 
2911  int64_to_numericvar((int64) val, &result);
2912 
2913  res = make_result(&result);
2914 
2915  free_var(&result);
2916 
2917  PG_RETURN_NUMERIC(res);
2918 }
2919 
2920 
2921 Datum
2923 {
2924  Numeric num = PG_GETARG_NUMERIC(0);
2925  NumericVar x;
2926  int32 result;
2927 
2928  /* XXX would it be better to return NULL? */
2929  if (NUMERIC_IS_NAN(num))
2930  ereport(ERROR,
2931  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2932  errmsg("cannot convert NaN to integer")));
2933 
2934  /* Convert to variable format, then convert to int4 */
2935  init_var_from_num(num, &x);
2936  result = numericvar_to_int32(&x);
2937  PG_RETURN_INT32(result);
2938 }
2939 
2940 /*
2941  * Given a NumericVar, convert it to an int32. If the NumericVar
2942  * exceeds the range of an int32, raise the appropriate error via
2943  * ereport(). The input NumericVar is *not* free'd.
2944  */
2945 static int32
2947 {
2948  int32 result;
2949  int64 val;
2950 
2951  if (!numericvar_to_int64(var, &val))
2952  ereport(ERROR,
2953  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
2954  errmsg("integer out of range")));
2955 
2956  /* Down-convert to int4 */
2957  result = (int32) val;
2958 
2959  /* Test for overflow by reverse-conversion. */
2960  if ((int64) result != val)
2961  ereport(ERROR,
2962  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
2963  errmsg("integer out of range")));
2964 
2965  return result;
2966 }
2967 
2968 Datum
2970 {
2971  int64 val = PG_GETARG_INT64(0);
2972  Numeric res;
2973  NumericVar result;
2974 
2975  init_var(&result);
2976 
2977  int64_to_numericvar(val, &result);
2978 
2979  res = make_result(&result);
2980 
2981  free_var(&result);
2982 
2983  PG_RETURN_NUMERIC(res);
2984 }
2985 
2986 
2987 Datum
2989 {
2990  Numeric num = PG_GETARG_NUMERIC(0);
2991  NumericVar x;
2992  int64 result;
2993 
2994  /* XXX would it be better to return NULL? */
2995  if (NUMERIC_IS_NAN(num))
2996  ereport(ERROR,
2997  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2998  errmsg("cannot convert NaN to bigint")));
2999 
3000  /* Convert to variable format and thence to int8 */
3001  init_var_from_num(num, &x);
3002 
3003  if (!numericvar_to_int64(&x, &result))
3004  ereport(ERROR,
3005  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
3006  errmsg("bigint out of range")));
3007 
3008  PG_RETURN_INT64(result);
3009 }
3010 
3011 
3012 Datum
3014 {
3015  int16 val = PG_GETARG_INT16(0);
3016  Numeric res;
3017  NumericVar result;
3018 
3019  init_var(&result);
3020 
3021  int64_to_numericvar((int64) val, &result);
3022 
3023  res = make_result(&result);
3024 
3025  free_var(&result);
3026 
3027  PG_RETURN_NUMERIC(res);
3028 }
3029 
3030 
3031 Datum
3033 {
3034  Numeric num = PG_GETARG_NUMERIC(0);
3035  NumericVar x;
3036  int64 val;
3037  int16 result;
3038 
3039  /* XXX would it be better to return NULL? */
3040  if (NUMERIC_IS_NAN(num))
3041  ereport(ERROR,
3042  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3043  errmsg("cannot convert NaN to smallint")));
3044 
3045  /* Convert to variable format and thence to int8 */
3046  init_var_from_num(num, &x);
3047 
3048  if (!numericvar_to_int64(&x, &val))
3049  ereport(ERROR,
3050  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
3051  errmsg("smallint out of range")));
3052 
3053  /* Down-convert to int2 */
3054  result = (int16) val;
3055 
3056  /* Test for overflow by reverse-conversion. */
3057  if ((int64) result != val)
3058  ereport(ERROR,
3059  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
3060  errmsg("smallint out of range")));
3061 
3062  PG_RETURN_INT16(result);
3063 }
3064 
3065 
3066 Datum
3068 {
3070  Numeric res;
3071  NumericVar result;
3072  char buf[DBL_DIG + 100];
3073 
3074  if (isnan(val))
3075  PG_RETURN_NUMERIC(make_result(&const_nan));
3076 
3077  sprintf(buf, "%.*g", DBL_DIG, val);
3078 
3079  init_var(&result);
3080 
3081  /* Assume we need not worry about leading/trailing spaces */
3082  (void) set_var_from_str(buf, buf, &result);
3083 
3084  res = make_result(&result);
3085 
3086  free_var(&result);
3087 
3088  PG_RETURN_NUMERIC(res);
3089 }
3090 
3091 
3092 Datum
3094 {
3095  Numeric num = PG_GETARG_NUMERIC(0);
3096  char *tmp;
3097  Datum result;
3098 
3099  if (NUMERIC_IS_NAN(num))
3101 
3103  NumericGetDatum(num)));
3104 
3106 
3107  pfree(tmp);
3108 
3109  PG_RETURN_DATUM(result);
3110 }
3111 
3112 
3113 /*
3114  * Convert numeric to float8; if out of range, return +/- HUGE_VAL
3115  *
3116  * (internal helper function, not directly callable from SQL)
3117  */
3118 Datum
3120 {
3121  Numeric num = PG_GETARG_NUMERIC(0);
3122  double val;
3123 
3124  if (NUMERIC_IS_NAN(num))
3126 
3127  val = numeric_to_double_no_overflow(num);
3128 
3129  PG_RETURN_FLOAT8(val);
3130 }
3131 
3132 Datum
3134 {
3136  Numeric res;
3137  NumericVar result;
3138  char buf[FLT_DIG + 100];
3139 
3140  if (isnan(val))
3141  PG_RETURN_NUMERIC(make_result(&const_nan));
3142 
3143  sprintf(buf, "%.*g", FLT_DIG, val);
3144 
3145  init_var(&result);
3146 
3147  /* Assume we need not worry about leading/trailing spaces */
3148  (void) set_var_from_str(buf, buf, &result);
3149 
3150  res = make_result(&result);
3151 
3152  free_var(&result);
3153 
3154  PG_RETURN_NUMERIC(res);
3155 }
3156 
3157 
3158 Datum
3160 {
3161  Numeric num = PG_GETARG_NUMERIC(0);
3162  char *tmp;
3163  Datum result;
3164 
3165  if (NUMERIC_IS_NAN(num))
3167 
3169  NumericGetDatum(num)));
3170 
3172 
3173  pfree(tmp);
3174 
3175  PG_RETURN_DATUM(result);
3176 }
3177 
3178 
3179 /* ----------------------------------------------------------------------
3180  *
3181  * Aggregate functions
3182  *
3183  * The transition datatype for all these aggregates is declared as INTERNAL.
3184  * Actually, it's a pointer to a NumericAggState allocated in the aggregate
3185  * context. The digit buffers for the NumericVars will be there too.
3186  *
3187  * On platforms which support 128-bit integers some aggregates instead use a
3188  * 128-bit integer based transition datatype to speed up calculations.
3189  *
3190  * ----------------------------------------------------------------------
3191  */
3192 
3193 typedef struct NumericAggState
3194 {
3195  bool calcSumX2; /* if true, calculate sumX2 */
3196  MemoryContext agg_context; /* context we're calculating in */
3197  int64 N; /* count of processed numbers */
3198  NumericSumAccum sumX; /* sum of processed numbers */
3199  NumericSumAccum sumX2; /* sum of squares of processed numbers */
3200  int maxScale; /* maximum scale seen so far */
3201  int64 maxScaleCount; /* number of values seen with maximum scale */
3202  int64 NaNcount; /* count of NaN values (not included in N!) */
3203 } NumericAggState;
3204 
3205 /*
3206  * Prepare state data for a numeric aggregate function that needs to compute
3207  * sum, count and optionally sum of squares of the input.
3208  */
3209 static NumericAggState *
3210 makeNumericAggState(FunctionCallInfo fcinfo, bool calcSumX2)
3211 {
3213  MemoryContext agg_context;
3214  MemoryContext old_context;
3215 
3216  if (!AggCheckCallContext(fcinfo, &agg_context))
3217  elog(ERROR, "aggregate function called in non-aggregate context");
3218 
3219  old_context = MemoryContextSwitchTo(agg_context);
3220 
3221  state = (NumericAggState *) palloc0(sizeof(NumericAggState));
3222  state->calcSumX2 = calcSumX2;
3223  state->agg_context = agg_context;
3224 
3225  MemoryContextSwitchTo(old_context);
3226 
3227  return state;
3228 }
3229 
3230 /*
3231  * Like makeNumericAggState(), but allocate the state in the current memory
3232  * context.
3233  */
3234 static NumericAggState *
3236 {
3238 
3239  state = (NumericAggState *) palloc0(sizeof(NumericAggState));
3240  state->calcSumX2 = calcSumX2;
3242 
3243  return state;
3244 }
3245 
3246 /*
3247  * Accumulate a new input value for numeric aggregate functions.
3248  */
3249 static void
3251 {
3252  NumericVar X;
3253  NumericVar X2;
3254  MemoryContext old_context;
3255 
3256  /* Count NaN inputs separately from all else */
3257  if (NUMERIC_IS_NAN(newval))
3258  {
3259  state->NaNcount++;
3260  return;
3261  }
3262 
3263  /* load processed number in short-lived context */
3264  init_var_from_num(newval, &X);
3265 
3266  /*
3267  * Track the highest input dscale that we've seen, to support inverse
3268  * transitions (see do_numeric_discard).
3269  */
3270  if (X.dscale > state->maxScale)
3271  {
3272  state->maxScale = X.dscale;
3273  state->maxScaleCount = 1;
3274  }
3275  else if (X.dscale == state->maxScale)
3276  state->maxScaleCount++;
3277 
3278  /* if we need X^2, calculate that in short-lived context */
3279  if (state->calcSumX2)
3280  {
3281  init_var(&X2);
3282  mul_var(&X, &X, &X2, X.dscale * 2);
3283  }
3284 
3285  /* The rest of this needs to work in the aggregate context */
3286  old_context = MemoryContextSwitchTo(state->agg_context);
3287 
3288  state->N++;
3289 
3290  /* Accumulate sums */
3291  accum_sum_add(&(state->sumX), &X);
3292 
3293  if (state->calcSumX2)
3294  accum_sum_add(&(state->sumX2), &X2);
3295 
3296  MemoryContextSwitchTo(old_context);
3297 }
3298 
3299 /*
3300  * Attempt to remove an input value from the aggregated state.
3301  *
3302  * If the value cannot be removed then the function will return false; the
3303  * possible reasons for failing are described below.
3304  *
3305  * If we aggregate the values 1.01 and 2 then the result will be 3.01.
3306  * If we are then asked to un-aggregate the 1.01 then we must fail as we
3307  * won't be able to tell what the new aggregated value's dscale should be.
3308  * We don't want to return 2.00 (dscale = 2), since the sum's dscale would
3309  * have been zero if we'd really aggregated only 2.
3310  *
3311  * Note: alternatively, we could count the number of inputs with each possible
3312  * dscale (up to some sane limit). Not yet clear if it's worth the trouble.
3313  */
3314 static bool
3316 {
3317  NumericVar X;
3318  NumericVar X2;
3319  MemoryContext old_context;
3320 
3321  /* Count NaN inputs separately from all else */
3322  if (NUMERIC_IS_NAN(newval))
3323  {
3324  state->NaNcount--;
3325  return true;
3326  }
3327 
3328  /* load processed number in short-lived context */
3329  init_var_from_num(newval, &X);
3330 
3331  /*
3332  * state->sumX's dscale is the maximum dscale of any of the inputs.
3333  * Removing the last input with that dscale would require us to recompute
3334  * the maximum dscale of the *remaining* inputs, which we cannot do unless
3335  * no more non-NaN inputs remain at all. So we report a failure instead,
3336  * and force the aggregation to be redone from scratch.
3337  */
3338  if (X.dscale == state->maxScale)
3339  {
3340  if (state->maxScaleCount > 1 || state->maxScale == 0)
3341  {
3342  /*
3343  * Some remaining inputs have same dscale, or dscale hasn't gotten
3344  * above zero anyway
3345  */
3346  state->maxScaleCount--;
3347  }
3348  else if (state->N == 1)
3349  {
3350  /* No remaining non-NaN inputs at all, so reset maxScale */
3351  state->maxScale = 0;
3352  state->maxScaleCount = 0;
3353  }
3354  else
3355  {
3356  /* Correct new maxScale is uncertain, must fail */
3357  return false;
3358  }
3359  }
3360 
3361  /* if we need X^2, calculate that in short-lived context */
3362  if (state->calcSumX2)
3363  {
3364  init_var(&X2);
3365  mul_var(&X, &X, &X2, X.dscale * 2);
3366  }
3367 
3368  /* The rest of this needs to work in the aggregate context */
3369  old_context = MemoryContextSwitchTo(state->agg_context);
3370 
3371  if (state->N-- > 1)
3372  {
3373  /* Negate X, to subtract it from the sum */
3374  X.sign = (X.sign == NUMERIC_POS ? NUMERIC_NEG : NUMERIC_POS);
3375  accum_sum_add(&(state->sumX), &X);
3376 
3377  if (state->calcSumX2)
3378  {
3379  /* Negate X^2. X^2 is always positive */
3380  X2.sign = NUMERIC_NEG;
3381  accum_sum_add(&(state->sumX2), &X2);
3382  }
3383  }
3384  else
3385  {
3386  /* Zero the sums */
3387  Assert(state->N == 0);
3388 
3389  accum_sum_reset(&state->sumX);
3390  if (state->calcSumX2)
3391  accum_sum_reset(&state->sumX2);
3392  }
3393 
3394  MemoryContextSwitchTo(old_context);
3395 
3396  return true;
3397 }
3398 
3399 /*
3400  * Generic transition function for numeric aggregates that require sumX2.
3401  */
3402 Datum
3404 {
3406 
3407  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
3408 
3409  /* Create the state data on the first call */
3410  if (state == NULL)
3411  state = makeNumericAggState(fcinfo, true);
3412 
3413  if (!PG_ARGISNULL(1))
3415 
3416  PG_RETURN_POINTER(state);
3417 }
3418 
3419 /*
3420  * Generic combine function for numeric aggregates which require sumX2
3421  */
3422 Datum
3424 {
3425  NumericAggState *state1;
3426  NumericAggState *state2;
3427  MemoryContext agg_context;
3428  MemoryContext old_context;
3429 
3430  if (!AggCheckCallContext(fcinfo, &agg_context))
3431  elog(ERROR, "aggregate function called in non-aggregate context");
3432 
3433  state1 = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
3434  state2 = PG_ARGISNULL(1) ? NULL : (NumericAggState *) PG_GETARG_POINTER(1);
3435 
3436  if (state2 == NULL)
3437  PG_RETURN_POINTER(state1);
3438 
3439  /* manually copy all fields from state2 to state1 */
3440  if (state1 == NULL)
3441  {
3442  old_context = MemoryContextSwitchTo(agg_context);
3443 
3444  state1 = makeNumericAggStateCurrentContext(true);
3445  state1->N = state2->N;
3446  state1->NaNcount = state2->NaNcount;
3447  state1->maxScale = state2->maxScale;
3448  state1->maxScaleCount = state2->maxScaleCount;
3449 
3450  accum_sum_copy(&state1->sumX, &state2->sumX);
3451  accum_sum_copy(&state1->sumX2, &state2->sumX2);
3452 
3453  MemoryContextSwitchTo(old_context);
3454 
3455  PG_RETURN_POINTER(state1);
3456  }
3457 
3458  if (state2->N > 0)
3459  {
3460  state1->N += state2->N;
3461  state1->NaNcount += state2->NaNcount;
3462 
3463  /*
3464  * These are currently only needed for moving aggregates, but let's do
3465  * the right thing anyway...
3466  */
3467  if (state2->maxScale > state1->maxScale)
3468  {
3469  state1->maxScale = state2->maxScale;
3470  state1->maxScaleCount = state2->maxScaleCount;
3471  }
3472  else if (state2->maxScale == state1->maxScale)
3473  state1->maxScaleCount += state2->maxScaleCount;
3474 
3475  /* The rest of this needs to work in the aggregate context */
3476  old_context = MemoryContextSwitchTo(agg_context);
3477 
3478  /* Accumulate sums */
3479  accum_sum_combine(&state1->sumX, &state2->sumX);
3480  accum_sum_combine(&state1->sumX2, &state2->sumX2);
3481 
3482  MemoryContextSwitchTo(old_context);
3483  }
3484  PG_RETURN_POINTER(state1);
3485 }
3486 
3487 /*
3488  * Generic transition function for numeric aggregates that don't require sumX2.
3489  */
3490 Datum
3492 {
3494 
3495  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
3496 
3497  /* Create the state data on the first call */
3498  if (state == NULL)
3499  state = makeNumericAggState(fcinfo, false);
3500 
3501  if (!PG_ARGISNULL(1))
3503 
3504  PG_RETURN_POINTER(state);
3505 }
3506 
3507 /*
3508  * Combine function for numeric aggregates which don't require sumX2
3509  */
3510 Datum
3512 {
3513  NumericAggState *state1;
3514  NumericAggState *state2;
3515  MemoryContext agg_context;
3516  MemoryContext old_context;
3517 
3518  if (!AggCheckCallContext(fcinfo, &agg_context))
3519  elog(ERROR, "aggregate function called in non-aggregate context");
3520 
3521  state1 = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
3522  state2 = PG_ARGISNULL(1) ? NULL : (NumericAggState *) PG_GETARG_POINTER(1);
3523 
3524  if (state2 == NULL)
3525  PG_RETURN_POINTER(state1);
3526 
3527  /* manually copy all fields from state2 to state1 */
3528  if (state1 == NULL)
3529  {
3530  old_context = MemoryContextSwitchTo(agg_context);
3531 
3532  state1 = makeNumericAggStateCurrentContext(false);
3533  state1->N = state2->N;
3534  state1->NaNcount = state2->NaNcount;
3535  state1->maxScale = state2->maxScale;
3536  state1->maxScaleCount = state2->maxScaleCount;
3537 
3538  accum_sum_copy(&state1->sumX, &state2->sumX);
3539 
3540  MemoryContextSwitchTo(old_context);
3541 
3542  PG_RETURN_POINTER(state1);
3543  }
3544 
3545  if (state2->N > 0)
3546  {
3547  state1->N += state2->N;
3548  state1->NaNcount += state2->NaNcount;
3549 
3550  /*
3551  * These are currently only needed for moving aggregates, but let's do
3552  * the right thing anyway...
3553  */
3554  if (state2->maxScale > state1->maxScale)
3555  {
3556  state1->maxScale = state2->maxScale;
3557  state1->maxScaleCount = state2->maxScaleCount;
3558  }
3559  else if (state2->maxScale == state1->maxScale)
3560  state1->maxScaleCount += state2->maxScaleCount;
3561 
3562  /* The rest of this needs to work in the aggregate context */
3563  old_context = MemoryContextSwitchTo(agg_context);
3564 
3565  /* Accumulate sums */
3566  accum_sum_combine(&state1->sumX, &state2->sumX);
3567 
3568  MemoryContextSwitchTo(old_context);
3569  }
3570  PG_RETURN_POINTER(state1);
3571 }
3572 
3573 /*
3574  * numeric_avg_serialize
3575  * Serialize NumericAggState for numeric aggregates that don't require
3576  * sumX2.
3577  */
3578 Datum
3580 {
3583  Datum temp;
3584  bytea *sumX;
3585  bytea *result;
3586  NumericVar tmp_var;
3587 
3588  /* Ensure we disallow calling when not in aggregate context */
3589  if (!AggCheckCallContext(fcinfo, NULL))
3590  elog(ERROR, "aggregate function called in non-aggregate context");
3591 
3592  state = (NumericAggState *) PG_GETARG_POINTER(0);
3593 
3594  /*
3595  * This is a little wasteful since make_result converts the NumericVar
3596  * into a Numeric and numeric_send converts it back again. Is it worth
3597  * splitting the tasks in numeric_send into separate functions to stop
3598  * this? Doing so would also remove the fmgr call overhead.
3599  */
3600  init_var(&tmp_var);
3601  accum_sum_final(&state->sumX, &tmp_var);
3602 
3604  NumericGetDatum(make_result(&tmp_var)));
3605  sumX = DatumGetByteaP(temp);
3606  free_var(&tmp_var);
3607 
3608  pq_begintypsend(&buf);
3609 
3610  /* N */
3611  pq_sendint64(&buf, state->N);
3612 
3613  /* sumX */
3614  pq_sendbytes(&buf, VARDATA(sumX), VARSIZE(sumX) - VARHDRSZ);
3615 
3616  /* maxScale */
3617  pq_sendint(&buf, state->maxScale, 4);
3618 
3619  /* maxScaleCount */
3620  pq_sendint64(&buf, state->maxScaleCount);
3621 
3622  /* NaNcount */
3623  pq_sendint64(&buf, state->NaNcount);
3624 
3625  result = pq_endtypsend(&buf);
3626 
3627  PG_RETURN_BYTEA_P(result);
3628 }
3629 
3630 /*
3631  * numeric_avg_deserialize
3632  * Deserialize bytea into NumericAggState for numeric aggregates that
3633  * don't require sumX2.
3634  */
3635 Datum
3637 {
3638  bytea *sstate;
3639  NumericAggState *result;
3640  Datum temp;
3641  NumericVar tmp_var;
3643 
3644  if (!AggCheckCallContext(fcinfo, NULL))
3645  elog(ERROR, "aggregate function called in non-aggregate context");
3646 
3647  sstate = PG_GETARG_BYTEA_P(0);
3648 
3649  /*
3650  * Copy the bytea into a StringInfo so that we can "receive" it using the
3651  * standard recv-function infrastructure.
3652  */
3653  initStringInfo(&buf);
3654  appendBinaryStringInfo(&buf, VARDATA(sstate), VARSIZE(sstate) - VARHDRSZ);
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 = DatumGetByteaP(temp);
3718 
3719  accum_sum_final(&state->sumX2, &tmp_var);
3721  NumericGetDatum(make_result(&tmp_var)));
3722  sumX2 = DatumGetByteaP(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(sumX), VARSIZE(sumX) - VARHDRSZ);
3733 
3734  /* sumX2 */
3735  pq_sendbytes(&buf, VARDATA(sumX2), VARSIZE(sumX2) - VARHDRSZ);
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;
3760  NumericAggState *result;
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_P(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);
3776  appendBinaryStringInfo(&buf, VARDATA(sstate), VARSIZE(sstate) - VARHDRSZ);
3777 
3778  result = makeNumericAggStateCurrentContext(false);
3779 
3780  /* N */
3781  result->N = pq_getmsgint64(&buf);
3782 
3783  /* sumX */
3785  PointerGetDatum(&buf),
3786  InvalidOid,
3787  -1);
3788  init_var_from_num(DatumGetNumeric(temp), &sumX_var);
3789  accum_sum_add(&(result->sumX), &sumX_var);
3790 
3791  /* sumX2 */
3793  PointerGetDatum(&buf),
3794  InvalidOid,
3795  -1);
3796  init_var_from_num(DatumGetNumeric(temp), &sumX2_var);
3797  accum_sum_add(&(result->sumX2), &sumX2_var);
3798 
3799  /* maxScale */
3800  result->maxScale = pq_getmsgint(&buf, 4);
3801 
3802  /* maxScaleCount */
3803  result->maxScaleCount = pq_getmsgint64(&buf);
3804 
3805  /* NaNcount */
3806  result->NaNcount = pq_getmsgint64(&buf);
3807 
3808  pq_getmsgend(&buf);
3809  pfree(buf.data);
3810 
3811  PG_RETURN_POINTER(result);
3812 }
3813 
3814 /*
3815  * Generic inverse transition function for numeric aggregates
3816  * (with or without requirement for X^2).
3817  */
3818 Datum
3820 {
3822 
3823  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
3824 
3825  /* Should not get here with no state */
3826  if (state == NULL)
3827  elog(ERROR, "numeric_accum_inv called with NULL state");
3828 
3829  if (!PG_ARGISNULL(1))
3830  {
3831  /* If we fail to perform the inverse transition, return NULL */
3832  if (!do_numeric_discard(state, PG_GETARG_NUMERIC(1)))
3833  PG_RETURN_NULL();
3834  }
3835 
3836  PG_RETURN_POINTER(state);
3837 }
3838 
3839 
3840 /*
3841  * Integer data types in general use Numeric accumulators to share code
3842  * and avoid risk of overflow.
3843  *
3844  * However for performance reasons optimized special-purpose accumulator
3845  * routines are used when possible.
3846  *
3847  * On platforms with 128-bit integer support, the 128-bit routines will be
3848  * used when sum(X) or sum(X*X) fit into 128-bit.
3849  *
3850  * For 16 and 32 bit inputs, the N and sum(X) fit into 64-bit so the 64-bit
3851  * accumulators will be used for SUM and AVG of these data types.
3852  */
3853 
3854 #ifdef HAVE_INT128
3855 typedef struct Int128AggState
3856 {
3857  bool calcSumX2; /* if true, calculate sumX2 */
3858  int64 N; /* count of processed numbers */
3859  int128 sumX; /* sum of processed numbers */
3860  int128 sumX2; /* sum of squares of processed numbers */
3861 } Int128AggState;
3862 
3863 /*
3864  * Prepare state data for a 128-bit aggregate function that needs to compute
3865  * sum, count and optionally sum of squares of the input.
3866  */
3867 static Int128AggState *
3868 makeInt128AggState(FunctionCallInfo fcinfo, bool calcSumX2)
3869 {
3870  Int128AggState *state;
3871  MemoryContext agg_context;
3872  MemoryContext old_context;
3873 
3874  if (!AggCheckCallContext(fcinfo, &agg_context))
3875  elog(ERROR, "aggregate function called in non-aggregate context");
3876 
3877  old_context = MemoryContextSwitchTo(agg_context);
3878 
3879  state = (Int128AggState *) palloc0(sizeof(Int128AggState));
3880  state->calcSumX2 = calcSumX2;
3881 
3882  MemoryContextSwitchTo(old_context);
3883 
3884  return state;
3885 }
3886 
3887 /*
3888  * Like makeInt128AggState(), but allocate the state in the current memory
3889  * context.
3890  */
3891 static Int128AggState *
3892 makeInt128AggStateCurrentContext(bool calcSumX2)
3893 {
3894  Int128AggState *state;
3895 
3896  state = (Int128AggState *) palloc0(sizeof(Int128AggState));
3897  state->calcSumX2 = calcSumX2;
3898 
3899  return state;
3900 }
3901 
3902 /*
3903  * Accumulate a new input value for 128-bit aggregate functions.
3904  */
3905 static void
3906 do_int128_accum(Int128AggState *state, int128 newval)
3907 {
3908  if (state->calcSumX2)
3909  state->sumX2 += newval * newval;
3910 
3911  state->sumX += newval;
3912  state->N++;
3913 }
3914 
3915 /*
3916  * Remove an input value from the aggregated state.
3917  */
3918 static void
3919 do_int128_discard(Int128AggState *state, int128 newval)
3920 {
3921  if (state->calcSumX2)
3922  state->sumX2 -= newval * newval;
3923 
3924  state->sumX -= newval;
3925  state->N--;
3926 }
3927 
3928 typedef Int128AggState PolyNumAggState;
3929 #define makePolyNumAggState makeInt128AggState
3930 #define makePolyNumAggStateCurrentContext makeInt128AggStateCurrentContext
3931 #else
3933 #define makePolyNumAggState makeNumericAggState
3934 #define makePolyNumAggStateCurrentContext makeNumericAggStateCurrentContext
3935 #endif
3936 
3937 Datum
3939 {
3940  PolyNumAggState *state;
3941 
3942  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
3943 
3944  /* Create the state data on the first call */
3945  if (state == NULL)
3946  state = makePolyNumAggState(fcinfo, true);
3947 
3948  if (!PG_ARGISNULL(1))
3949  {
3950 #ifdef HAVE_INT128
3951  do_int128_accum(state, (int128) PG_GETARG_INT16(1));
3952 #else
3953  Numeric newval;
3954 
3956  PG_GETARG_DATUM(1)));
3957  do_numeric_accum(state, newval);
3958 #endif
3959  }
3960 
3961  PG_RETURN_POINTER(state);
3962 }
3963 
3964 Datum
3966 {
3967  PolyNumAggState *state;
3968 
3969  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
3970 
3971  /* Create the state data on the first call */
3972  if (state == NULL)
3973  state = makePolyNumAggState(fcinfo, true);
3974 
3975  if (!PG_ARGISNULL(1))
3976  {
3977 #ifdef HAVE_INT128
3978  do_int128_accum(state, (int128) PG_GETARG_INT32(1));
3979 #else
3980  Numeric newval;
3981 
3983  PG_GETARG_DATUM(1)));
3984  do_numeric_accum(state, newval);
3985 #endif
3986  }
3987 
3988  PG_RETURN_POINTER(state);
3989 }
3990 
3991 Datum
3993 {
3994  NumericAggState *state;
3995 
3996  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
3997 
3998  /* Create the state data on the first call */
3999  if (state == NULL)
4000  state = makeNumericAggState(fcinfo, true);
4001 
4002  if (!PG_ARGISNULL(1))
4003  {
4004  Numeric newval;
4005 
4007  PG_GETARG_DATUM(1)));
4008  do_numeric_accum(state, newval);
4009  }
4010 
4011  PG_RETURN_POINTER(state);
4012 }
4013 
4014 /*
4015  * Combine function for numeric aggregates which require sumX2
4016  */
4017 Datum
4019 {
4020  PolyNumAggState *state1;
4021  PolyNumAggState *state2;
4022  MemoryContext agg_context;
4023  MemoryContext old_context;
4024 
4025  if (!AggCheckCallContext(fcinfo, &agg_context))
4026  elog(ERROR, "aggregate function called in non-aggregate context");
4027 
4028  state1 = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4029  state2 = PG_ARGISNULL(1) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(1);
4030 
4031  if (state2 == NULL)
4032  PG_RETURN_POINTER(state1);
4033 
4034  /* manually copy all fields from state2 to state1 */
4035  if (state1 == NULL)
4036  {
4037  old_context = MemoryContextSwitchTo(agg_context);
4038 
4039  state1 = makePolyNumAggState(fcinfo, true);
4040  state1->N = state2->N;
4041 
4042 #ifdef HAVE_INT128
4043  state1->sumX = state2->sumX;
4044  state1->sumX2 = state2->sumX2;
4045 #else
4046  accum_sum_copy(&state2->sumX, &state1->sumX);
4047  accum_sum_copy(&state2->sumX2, &state1->sumX2);
4048 #endif
4049 
4050  MemoryContextSwitchTo(old_context);
4051 
4052  PG_RETURN_POINTER(state1);
4053  }
4054 
4055  if (state2->N > 0)
4056  {
4057  state1->N += state2->N;
4058 
4059 #ifdef HAVE_INT128
4060  state1->sumX += state2->sumX;
4061  state1->sumX2 += state2->sumX2;
4062 #else
4063  /* The rest of this needs to work in the aggregate context */
4064  old_context = MemoryContextSwitchTo(agg_context);
4065 
4066  /* Accumulate sums */
4067  accum_sum_combine(&state1->sumX, &state2->sumX);
4068  accum_sum_combine(&state1->sumX2, &state2->sumX2);
4069 
4070  MemoryContextSwitchTo(old_context);
4071 #endif
4072 
4073  }
4074  PG_RETURN_POINTER(state1);
4075 }
4076 
4077 /*
4078  * numeric_poly_serialize
4079  * Serialize PolyNumAggState into bytea for aggregate functions which
4080  * require sumX2.
4081  */
4082 Datum
4084 {
4085  PolyNumAggState *state;
4087  bytea *sumX;
4088  bytea *sumX2;
4089  bytea *result;
4090 
4091  /* Ensure we disallow calling when not in aggregate context */
4092  if (!AggCheckCallContext(fcinfo, NULL))
4093  elog(ERROR, "aggregate function called in non-aggregate context");
4094 
4095  state = (PolyNumAggState *) PG_GETARG_POINTER(0);
4096 
4097  /*
4098  * If the platform supports int128 then sumX and sumX2 will be a 128 bit
4099  * integer type. Here we'll convert that into a numeric type so that the
4100  * combine state is in the same format for both int128 enabled machines
4101  * and machines which don't support that type. The logic here is that one
4102  * day we might like to send these over to another server for further
4103  * processing and we want a standard format to work with.
4104  */
4105  {
4106  Datum temp;
4107  NumericVar num;
4108 
4109  init_var(&num);
4110 
4111 #ifdef HAVE_INT128
4112  int128_to_numericvar(state->sumX, &num);
4113 #else
4114  accum_sum_final(&state->sumX, &num);
4115 #endif
4117  NumericGetDatum(make_result(&num)));
4118  sumX = DatumGetByteaP(temp);
4119 
4120 #ifdef HAVE_INT128
4121  int128_to_numericvar(state->sumX2, &num);
4122 #else
4123  accum_sum_final(&state->sumX2, &num);
4124 #endif
4126  NumericGetDatum(make_result(&num)));
4127  sumX2 = DatumGetByteaP(temp);
4128 
4129  free_var(&num);
4130  }
4131 
4132  pq_begintypsend(&buf);
4133 
4134  /* N */
4135  pq_sendint64(&buf, state->N);
4136 
4137  /* sumX */
4138  pq_sendbytes(&buf, VARDATA(sumX), VARSIZE(sumX) - VARHDRSZ);
4139 
4140  /* sumX2 */
4141  pq_sendbytes(&buf, VARDATA(sumX2), VARSIZE(sumX2) - VARHDRSZ);
4142 
4143  result = pq_endtypsend(&buf);
4144 
4145  PG_RETURN_BYTEA_P(result);
4146 }
4147 
4148 /*
4149  * numeric_poly_deserialize
4150  * Deserialize PolyNumAggState from bytea for aggregate functions which
4151  * require sumX2.
4152  */
4153 Datum
4155 {
4156  bytea *sstate;
4157  PolyNumAggState *result;
4158  Datum sumX;
4159  NumericVar sumX_var;
4160  Datum sumX2;
4161  NumericVar sumX2_var;
4163 
4164  if (!AggCheckCallContext(fcinfo, NULL))
4165  elog(ERROR, "aggregate function called in non-aggregate context");
4166 
4167  sstate = PG_GETARG_BYTEA_P(0);
4168 
4169  /*
4170  * Copy the bytea into a StringInfo so that we can "receive" it using the
4171  * standard recv-function infrastructure.
4172  */
4173  initStringInfo(&buf);
4174  appendBinaryStringInfo(&buf, VARDATA(sstate), VARSIZE(sstate) - VARHDRSZ);
4175 
4176  result = makePolyNumAggStateCurrentContext(false);
4177 
4178  /* N */
4179  result->N = pq_getmsgint64(&buf);
4180 
4181  /* sumX */
4183  PointerGetDatum(&buf),
4184  InvalidOid,
4185  -1);
4186 
4187  /* sumX2 */
4189  PointerGetDatum(&buf),
4190  InvalidOid,
4191  -1);
4192 
4193  init_var_from_num(DatumGetNumeric(sumX), &sumX_var);
4194 #ifdef HAVE_INT128
4195  numericvar_to_int128(&sumX_var, &result->sumX);
4196 #else
4197  accum_sum_add(&result->sumX, &sumX_var);
4198 #endif
4199 
4200  init_var_from_num(DatumGetNumeric(sumX2), &sumX2_var);
4201 #ifdef HAVE_INT128
4202  numericvar_to_int128(&sumX2_var, &result->sumX2);
4203 #else
4204  accum_sum_add(&result->sumX2, &sumX2_var);
4205 #endif
4206 
4207  pq_getmsgend(&buf);
4208  pfree(buf.data);
4209 
4210  PG_RETURN_POINTER(result);
4211 }
4212 
4213 /*
4214  * Transition function for int8 input when we don't need sumX2.
4215  */
4216 Datum
4218 {
4219  PolyNumAggState *state;
4220 
4221  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4222 
4223  /* Create the state data on the first call */
4224  if (state == NULL)
4225  state = makePolyNumAggState(fcinfo, false);
4226 
4227  if (!PG_ARGISNULL(1))
4228  {
4229 #ifdef HAVE_INT128
4230  do_int128_accum(state, (int128) PG_GETARG_INT64(1));
4231 #else
4232  Numeric newval;
4233 
4235  PG_GETARG_DATUM(1)));
4236  do_numeric_accum(state, newval);
4237 #endif
4238  }
4239 
4240  PG_RETURN_POINTER(state);
4241 }
4242 
4243 /*
4244  * Combine function for PolyNumAggState for aggregates which don't require
4245  * sumX2
4246  */
4247 Datum
4249 {
4250  PolyNumAggState *state1;
4251  PolyNumAggState *state2;
4252  MemoryContext agg_context;
4253  MemoryContext old_context;
4254 
4255  if (!AggCheckCallContext(fcinfo, &agg_context))
4256  elog(ERROR, "aggregate function called in non-aggregate context");
4257 
4258  state1 = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4259  state2 = PG_ARGISNULL(1) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(1);
4260 
4261  if (state2 == NULL)
4262  PG_RETURN_POINTER(state1);
4263 
4264  /* manually copy all fields from state2 to state1 */
4265  if (state1 == NULL)
4266  {
4267  old_context = MemoryContextSwitchTo(agg_context);
4268 
4269  state1 = makePolyNumAggState(fcinfo, false);
4270  state1->N = state2->N;
4271 
4272 #ifdef HAVE_INT128
4273  state1->sumX = state2->sumX;
4274 #else
4275  accum_sum_copy(&state1->sumX, &state2->sumX);
4276 #endif
4277  MemoryContextSwitchTo(old_context);
4278 
4279  PG_RETURN_POINTER(state1);
4280  }
4281 
4282  if (state2->N > 0)
4283  {
4284  state1->N += state2->N;
4285 
4286 #ifdef HAVE_INT128
4287  state1->sumX += state2->sumX;
4288 #else
4289  /* The rest of this needs to work in the aggregate context */
4290  old_context = MemoryContextSwitchTo(agg_context);
4291 
4292  /* Accumulate sums */
4293  accum_sum_combine(&state1->sumX, &state2->sumX);
4294 
4295  MemoryContextSwitchTo(old_context);
4296 #endif
4297 
4298  }
4299  PG_RETURN_POINTER(state1);
4300 }
4301 
4302 /*
4303  * int8_avg_serialize
4304  * Serialize PolyNumAggState into bytea using the standard
4305  * recv-function infrastructure.
4306  */
4307 Datum
4309 {
4310  PolyNumAggState *state;
4312  bytea *sumX;
4313  bytea *result;
4314 
4315  /* Ensure we disallow calling when not in aggregate context */
4316  if (!AggCheckCallContext(fcinfo, NULL))
4317  elog(ERROR, "aggregate function called in non-aggregate context");
4318 
4319  state = (PolyNumAggState *) PG_GETARG_POINTER(0);
4320 
4321  /*
4322  * If the platform supports int128 then sumX will be a 128 integer type.
4323  * Here we'll convert that into a numeric type so that the combine state
4324  * is in the same format for both int128 enabled machines and machines
4325  * which don't support that type. The logic here is that one day we might
4326  * like to send these over to another server for further processing and we
4327  * want a standard format to work with.
4328  */
4329  {
4330  Datum temp;
4331  NumericVar num;
4332 
4333  init_var(&num);
4334 
4335 #ifdef HAVE_INT128
4336  int128_to_numericvar(state->sumX, &num);
4337 #else
4338  accum_sum_final(&state->sumX, &num);
4339 #endif
4341  NumericGetDatum(make_result(&num)));
4342  sumX = DatumGetByteaP(temp);
4343 
4344  free_var(&num);
4345  }
4346 
4347  pq_begintypsend(&buf);
4348 
4349  /* N */
4350  pq_sendint64(&buf, state->N);
4351 
4352  /* sumX */
4353  pq_sendbytes(&buf, VARDATA(sumX), VARSIZE(sumX) - VARHDRSZ);
4354 
4355  result = pq_endtypsend(&buf);
4356 
4357  PG_RETURN_BYTEA_P(result);
4358 }
4359 
4360 /*
4361  * int8_avg_deserialize
4362  * Deserialize bytea back into PolyNumAggState.
4363  */
4364 Datum
4366 {
4367  bytea *sstate;
4368  PolyNumAggState *result;
4370  Datum temp;
4371  NumericVar num;
4372 
4373  if (!AggCheckCallContext(fcinfo, NULL))
4374  elog(ERROR, "aggregate function called in non-aggregate context");
4375 
4376  sstate = PG_GETARG_BYTEA_P(0);
4377 
4378  /*
4379  * Copy the bytea into a StringInfo so that we can "receive" it using the
4380  * standard recv-function infrastructure.
4381  */
4382  initStringInfo(&buf);
4383  appendBinaryStringInfo(&buf, VARDATA(sstate), VARSIZE(sstate) - VARHDRSZ);
4384 
4385  result = makePolyNumAggStateCurrentContext(false);
4386 
4387  /* N */
4388  result->N = pq_getmsgint64(&buf);
4389 
4390  /* sumX */
4392  PointerGetDatum(&buf),
4393  InvalidOid,
4394  -1);
4395  init_var_from_num(DatumGetNumeric(temp), &num);
4396 #ifdef HAVE_INT128
4397  numericvar_to_int128(&num, &result->sumX);
4398 #else
4399  accum_sum_add(&result->sumX, &num);
4400 #endif
4401 
4402  pq_getmsgend(&buf);
4403  pfree(buf.data);
4404 
4405  PG_RETURN_POINTER(result);
4406 }
4407 
4408 /*
4409  * Inverse transition functions to go with the above.
4410  */
4411 
4412 Datum
4414 {
4415  PolyNumAggState *state;
4416 
4417  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4418 
4419  /* Should not get here with no state */
4420  if (state == NULL)
4421  elog(ERROR, "int2_accum_inv called with NULL state");
4422 
4423  if (!PG_ARGISNULL(1))
4424  {
4425 #ifdef HAVE_INT128
4426  do_int128_discard(state, (int128) PG_GETARG_INT16(1));
4427 #else
4428  Numeric newval;
4429 
4431  PG_GETARG_DATUM(1)));
4432 
4433  /* Should never fail, all inputs have dscale 0 */
4434  if (!do_numeric_discard(state, newval))
4435  elog(ERROR, "do_numeric_discard failed unexpectedly");
4436 #endif
4437  }
4438 
4439  PG_RETURN_POINTER(state);
4440 }
4441 
4442 Datum
4444 {
4445  PolyNumAggState *state;
4446 
4447  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4448 
4449  /* Should not get here with no state */
4450  if (state == NULL)
4451  elog(ERROR, "int4_accum_inv called with NULL state");
4452 
4453  if (!PG_ARGISNULL(1))
4454  {
4455 #ifdef HAVE_INT128
4456  do_int128_discard(state, (int128) PG_GETARG_INT32(1));
4457 #else
4458  Numeric newval;
4459 
4461  PG_GETARG_DATUM(1)));
4462 
4463  /* Should never fail, all inputs have dscale 0 */
4464  if (!do_numeric_discard(state, newval))
4465  elog(ERROR, "do_numeric_discard failed unexpectedly");
4466 #endif
4467  }
4468 
4469  PG_RETURN_POINTER(state);
4470 }
4471 
4472 Datum
4474 {
4475  NumericAggState *state;
4476 
4477  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
4478 
4479  /* Should not get here with no state */
4480  if (state == NULL)
4481  elog(ERROR, "int8_accum_inv called with NULL state");
4482 
4483  if (!PG_ARGISNULL(1))
4484  {
4485  Numeric newval;
4486 
4488  PG_GETARG_DATUM(1)));
4489 
4490  /* Should never fail, all inputs have dscale 0 */
4491  if (!do_numeric_discard(state, newval))
4492  elog(ERROR, "do_numeric_discard failed unexpectedly");
4493  }
4494 
4495  PG_RETURN_POINTER(state);
4496 }
4497 
4498 Datum
4500 {
4501  PolyNumAggState *state;
4502 
4503  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4504 
4505  /* Should not get here with no state */
4506  if (state == NULL)
4507  elog(ERROR, "int8_avg_accum_inv called with NULL state");
4508 
4509  if (!PG_ARGISNULL(1))
4510  {
4511 #ifdef HAVE_INT128
4512  do_int128_discard(state, (int128) PG_GETARG_INT64(1));
4513 #else
4514  Numeric newval;
4515 
4517  PG_GETARG_DATUM(1)));
4518 
4519  /* Should never fail, all inputs have dscale 0 */
4520  if (!do_numeric_discard(state, newval))
4521  elog(ERROR, "do_numeric_discard failed unexpectedly");
4522 #endif
4523  }
4524 
4525  PG_RETURN_POINTER(state);
4526 }
4527 
4528 Datum
4530 {
4531 #ifdef HAVE_INT128
4532  PolyNumAggState *state;
4533  Numeric res;
4534  NumericVar result;
4535 
4536  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4537 
4538  /* If there were no non-null inputs, return NULL */
4539  if (state == NULL || state->N == 0)
4540  PG_RETURN_NULL();
4541 
4542  init_var(&result);
4543 
4544  int128_to_numericvar(state->sumX, &result);
4545 
4546  res = make_result(&result);
4547 
4548  free_var(&result);
4549 
4550  PG_RETURN_NUMERIC(res);
4551 #else
4552  return numeric_sum(fcinfo);
4553 #endif
4554 }
4555 
4556 Datum
4558 {
4559 #ifdef HAVE_INT128
4560  PolyNumAggState *state;
4561  NumericVar result;
4562  Datum countd,
4563  sumd;
4564 
4565  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4566 
4567  /* If there were no non-null inputs, return NULL */
4568  if (state == NULL || state->N == 0)
4569  PG_RETURN_NULL();
4570 
4571  init_var(&result);
4572 
4573  int128_to_numericvar(state->sumX, &result);
4574 
4576  Int64GetDatumFast(state->N));
4577  sumd = NumericGetDatum(make_result(&result));
4578 
4579  free_var(&result);
4580 
4582 #else
4583  return numeric_avg(fcinfo);
4584 #endif
4585 }
4586 
4587 Datum
4589 {
4590  NumericAggState *state;
4591  Datum N_datum;
4592  Datum sumX_datum;
4593  NumericVar sumX_var;
4594 
4595  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
4596 
4597  /* If there were no non-null inputs, return NULL */
4598  if (state == NULL || (state->N + state->NaNcount) == 0)
4599  PG_RETURN_NULL();
4600 
4601  if (state->NaNcount > 0) /* there was at least one NaN input */
4602  PG_RETURN_NUMERIC(make_result(&const_nan));
4603 
4604  N_datum = DirectFunctionCall1(int8_numeric, Int64GetDatum(state->N));
4605 
4606  init_var(&sumX_var);
4607  accum_sum_final(&state->sumX, &sumX_var);
4608  sumX_datum = NumericGetDatum(make_result(&sumX_var));
4609  free_var(&sumX_var);
4610 
4611  PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumX_datum, N_datum));
4612 }
4613 
4614 Datum
4616 {
4617  NumericAggState *state;
4618  NumericVar sumX_var;
4619  Numeric result;
4620 
4621  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
4622 
4623  /* If there were no non-null inputs, return NULL */
4624  if (state == NULL || (state->N + state->NaNcount) == 0)
4625  PG_RETURN_NULL();
4626 
4627  if (state->NaNcount > 0) /* there was at least one NaN input */
4628  PG_RETURN_NUMERIC(make_result(&const_nan));
4629 
4630  init_var(&sumX_var);
4631  accum_sum_final(&state->sumX, &sumX_var);
4632  result = make_result(&sumX_var);
4633  free_var(&sumX_var);
4634 
4635  PG_RETURN_NUMERIC(result);
4636 }
4637 
4638 /*
4639  * Workhorse routine for the standard deviance and variance
4640  * aggregates. 'state' is aggregate's transition state.
4641  * 'variance' specifies whether we should calculate the
4642  * variance or the standard deviation. 'sample' indicates whether the
4643  * caller is interested in the sample or the population
4644  * variance/stddev.
4645  *
4646  * If appropriate variance statistic is undefined for the input,
4647  * *is_null is set to true and NULL is returned.
4648  */
4649 static Numeric
4651  bool variance, bool sample,
4652  bool *is_null)
4653 {
4654  Numeric res;
4655  NumericVar vN,
4656  vsumX,
4657  vsumX2,
4658  vNminus1;
4659  NumericVar *comp;
4660  int rscale;
4661 
4662  /* Deal with empty input and NaN-input cases */
4663  if (state == NULL || (state->N + state->NaNcount) == 0)
4664  {
4665  *is_null = true;
4666  return NULL;
4667  }
4668 
4669  *is_null = false;
4670 
4671  if (state->NaNcount > 0)
4672  return make_result(&const_nan);
4673 
4674  init_var(&vN);
4675  init_var(&vsumX);
4676  init_var(&vsumX2);
4677 
4678  int64_to_numericvar(state->N, &vN);
4679  accum_sum_final(&(state->sumX), &vsumX);
4680  accum_sum_final(&(state->sumX2), &vsumX2);
4681 
4682  /*
4683  * Sample stddev and variance are undefined when N <= 1; population stddev
4684  * is undefined when N == 0. Return NULL in either case.
4685  */
4686  if (sample)
4687  comp = &const_one;
4688  else
4689  comp = &const_zero;
4690 
4691  if (cmp_var(&vN, comp) <= 0)
4692  {
4693  *is_null = true;
4694  return NULL;
4695  }
4696 
4697  init_var(&vNminus1);
4698  sub_var(&vN, &const_one, &vNminus1);
4699 
4700  /* compute rscale for mul_var calls */
4701  rscale = vsumX.dscale * 2;
4702 
4703  mul_var(&vsumX, &vsumX, &vsumX, rscale); /* vsumX = sumX * sumX */
4704  mul_var(&vN, &vsumX2, &vsumX2, rscale); /* vsumX2 = N * sumX2 */
4705  sub_var(&vsumX2, &vsumX, &vsumX2); /* N * sumX2 - sumX * sumX */
4706 
4707  if (cmp_var(&vsumX2, &const_zero) <= 0)
4708  {
4709  /* Watch out for roundoff error producing a negative numerator */
4710  res = make_result(&const_zero);
4711  }
4712  else
4713  {
4714  if (sample)
4715  mul_var(&vN, &vNminus1, &vNminus1, 0); /* N * (N - 1) */
4716  else
4717  mul_var(&vN, &vN, &vNminus1, 0); /* N * N */
4718  rscale = select_div_scale(&vsumX2, &vNminus1);
4719  div_var(&vsumX2, &vNminus1, &vsumX, rscale, true); /* variance */
4720  if (!variance)
4721  sqrt_var(&vsumX, &vsumX, rscale); /* stddev */
4722 
4723  res = make_result(&vsumX);
4724  }
4725 
4726  free_var(&vNminus1);
4727  free_var(&vsumX);
4728  free_var(&vsumX2);
4729 
4730  return res;
4731 }
4732 
4733 Datum
4735 {
4736  NumericAggState *state;
4737  Numeric res;
4738  bool is_null;
4739 
4740  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
4741 
4742  res = numeric_stddev_internal(state, true, true, &is_null);
4743 
4744  if (is_null)
4745  PG_RETURN_NULL();
4746  else
4747  PG_RETURN_NUMERIC(res);
4748 }
4749 
4750 Datum
4752 {
4753  NumericAggState *state;
4754  Numeric res;
4755  bool is_null;
4756 
4757  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
4758 
4759  res = numeric_stddev_internal(state, false, true, &is_null);
4760 
4761  if (is_null)
4762  PG_RETURN_NULL();
4763  else
4764  PG_RETURN_NUMERIC(res);
4765 }
4766 
4767 Datum
4769 {
4770  NumericAggState *state;
4771  Numeric res;
4772  bool is_null;
4773 
4774  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
4775 
4776  res = numeric_stddev_internal(state, true, false, &is_null);
4777 
4778  if (is_null)
4779  PG_RETURN_NULL();
4780  else
4781  PG_RETURN_NUMERIC(res);
4782 }
4783 
4784 Datum
4786 {
4787  NumericAggState *state;
4788  Numeric res;
4789  bool is_null;
4790 
4791  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
4792 
4793  res = numeric_stddev_internal(state, false, false, &is_null);
4794 
4795  if (is_null)
4796  PG_RETURN_NULL();
4797  else
4798  PG_RETURN_NUMERIC(res);
4799 }
4800 
4801 #ifdef HAVE_INT128
4802 static Numeric
4803 numeric_poly_stddev_internal(Int128AggState *state,
4804  bool variance, bool sample,
4805  bool *is_null)
4806 {
4807  NumericAggState numstate;
4808  Numeric res;
4809 
4810  /* Initialize an empty agg state */
4811  memset(&numstate, 0, sizeof(NumericAggState));
4812 
4813  if (state)
4814  {
4815  NumericVar tmp_var;
4816 
4817  numstate.N = state->N;
4818 
4819  init_var(&tmp_var);
4820 
4821  int128_to_numericvar(state->sumX, &tmp_var);
4822  accum_sum_add(&numstate.sumX, &tmp_var);
4823 
4824  int128_to_numericvar(state->sumX2, &tmp_var);
4825  accum_sum_add(&numstate.sumX2, &tmp_var);
4826 
4827  free_var(&tmp_var);
4828  }
4829 
4830  res = numeric_stddev_internal(&numstate, variance, sample, is_null);
4831 
4832  if (numstate.sumX.ndigits > 0)
4833  {
4834  pfree(numstate.sumX.pos_digits);
4835  pfree(numstate.sumX.neg_digits);
4836  }
4837  if (numstate.sumX2.ndigits > 0)
4838  {
4839  pfree(numstate.sumX2.pos_digits);
4840  pfree(numstate.sumX2.neg_digits);
4841  }
4842 
4843  return res;
4844 }
4845 #endif
4846 
4847 Datum
4849 {
4850 #ifdef HAVE_INT128
4851  PolyNumAggState *state;
4852  Numeric res;
4853  bool is_null;
4854 
4855  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4856 
4857  res = numeric_poly_stddev_internal(state, true, true, &is_null);
4858 
4859  if (is_null)
4860  PG_RETURN_NULL();
4861  else
4862  PG_RETURN_NUMERIC(res);
4863 #else
4864  return numeric_var_samp(fcinfo);
4865 #endif
4866 }
4867 
4868 Datum
4870 {
4871 #ifdef HAVE_INT128
4872  PolyNumAggState *state;
4873  Numeric res;
4874  bool is_null;
4875 
4876  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4877 
4878  res = numeric_poly_stddev_internal(state, false, true, &is_null);
4879 
4880  if (is_null)
4881  PG_RETURN_NULL();
4882  else
4883  PG_RETURN_NUMERIC(res);
4884 #else
4885  return numeric_stddev_samp(fcinfo);
4886 #endif
4887 }
4888 
4889 Datum
4891 {
4892 #ifdef HAVE_INT128
4893  PolyNumAggState *state;
4894  Numeric res;
4895  bool is_null;
4896 
4897  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4898 
4899  res = numeric_poly_stddev_internal(state, true, false, &is_null);
4900 
4901  if (is_null)
4902  PG_RETURN_NULL();
4903  else
4904  PG_RETURN_NUMERIC(res);
4905 #else
4906  return numeric_var_pop(fcinfo);
4907 #endif
4908 }
4909 
4910 Datum
4912 {
4913 #ifdef HAVE_INT128
4914  PolyNumAggState *state;
4915  Numeric res;
4916  bool is_null;
4917 
4918  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
4919 
4920  res = numeric_poly_stddev_internal(state, false, false, &is_null);
4921 
4922  if (is_null)
4923  PG_RETURN_NULL();
4924  else
4925  PG_RETURN_NUMERIC(res);
4926 #else
4927  return numeric_stddev_pop(fcinfo);
4928 #endif
4929 }
4930 
4931 /*
4932  * SUM transition functions for integer datatypes.
4933  *
4934  * To avoid overflow, we use accumulators wider than the input datatype.
4935  * A Numeric accumulator is needed for int8 input; for int4 and int2
4936  * inputs, we use int8 accumulators which should be sufficient for practical
4937  * purposes. (The latter two therefore don't really belong in this file,
4938  * but we keep them here anyway.)
4939  *
4940  * Because SQL defines the SUM() of no values to be NULL, not zero,
4941  * the initial condition of the transition data value needs to be NULL. This
4942  * means we can't rely on ExecAgg to automatically insert the first non-null
4943  * data value into the transition data: it doesn't know how to do the type
4944  * conversion. The upshot is that these routines have to be marked non-strict
4945  * and handle substitution of the first non-null input themselves.
4946  *
4947  * Note: these functions are used only in plain aggregation mode.
4948  * In moving-aggregate mode, we use intX_avg_accum and intX_avg_accum_inv.
4949  */
4950 
4951 Datum
4953 {
4954  int64 newval;
4955 
4956  if (PG_ARGISNULL(0))
4957  {
4958  /* No non-null input seen so far... */
4959  if (PG_ARGISNULL(1))
4960  PG_RETURN_NULL(); /* still no non-null */
4961  /* This is the first non-null input. */
4962  newval = (int64) PG_GETARG_INT16(1);
4963  PG_RETURN_INT64(newval);
4964  }
4965 
4966  /*
4967  * If we're invoked as an aggregate, we can cheat and modify our first
4968  * parameter in-place to avoid palloc overhead. If not, we need to return
4969  * the new value of the transition variable. (If int8 is pass-by-value,
4970  * then of course this is useless as well as incorrect, so just ifdef it
4971  * out.)
4972  */
4973 #ifndef USE_FLOAT8_BYVAL /* controls int8 too */
4974  if (AggCheckCallContext(fcinfo, NULL))
4975  {
4976  int64 *oldsum = (int64 *) PG_GETARG_POINTER(0);
4977 
4978  /* Leave the running sum unchanged in the new input is null */
4979  if (!PG_ARGISNULL(1))
4980  *oldsum = *oldsum + (int64) PG_GETARG_INT16(1);
4981 
4982  PG_RETURN_POINTER(oldsum);
4983  }
4984  else
4985 #endif
4986  {
4987  int64 oldsum = PG_GETARG_INT64(0);
4988 
4989  /* Leave sum unchanged if new input is null. */
4990  if (PG_ARGISNULL(1))
4991  PG_RETURN_INT64(oldsum);
4992 
4993  /* OK to do the addition. */
4994  newval = oldsum + (int64) PG_GETARG_INT16(1);
4995 
4996  PG_RETURN_INT64(newval);
4997  }
4998 }
4999 
5000 Datum
5002 {
5003  int64 newval;
5004 
5005  if (PG_ARGISNULL(0))
5006  {
5007  /* No non-null input seen so far... */
5008  if (PG_ARGISNULL(1))
5009  PG_RETURN_NULL(); /* still no non-null */
5010  /* This is the first non-null input. */
5011  newval = (int64) PG_GETARG_INT32(1);
5012  PG_RETURN_INT64(newval);
5013  }
5014 
5015  /*
5016  * If we're invoked as an aggregate, we can cheat and modify our first
5017  * parameter in-place to avoid palloc overhead. If not, we need to return
5018  * the new value of the transition variable. (If int8 is pass-by-value,
5019  * then of course this is useless as well as incorrect, so just ifdef it
5020  * out.)
5021  */
5022 #ifndef USE_FLOAT8_BYVAL /* controls int8 too */
5023  if (AggCheckCallContext(fcinfo, NULL))
5024  {
5025  int64 *oldsum = (int64 *) PG_GETARG_POINTER(0);
5026 
5027  /* Leave the running sum unchanged in the new input is null */
5028  if (!PG_ARGISNULL(1))
5029  *oldsum = *oldsum + (int64) PG_GETARG_INT32(1);
5030 
5031  PG_RETURN_POINTER(oldsum);
5032  }
5033  else
5034 #endif
5035  {
5036  int64 oldsum = PG_GETARG_INT64(0);
5037 
5038  /* Leave sum unchanged if new input is null. */
5039  if (PG_ARGISNULL(1))
5040  PG_RETURN_INT64(oldsum);
5041 
5042  /* OK to do the addition. */
5043  newval = oldsum + (int64) PG_GETARG_INT32(1);
5044 
5045  PG_RETURN_INT64(newval);
5046  }
5047 }
5048 
5049 /*
5050  * Note: this function is obsolete, it's no longer used for SUM(int8).
5051  */
5052 Datum
5054 {
5055  Numeric oldsum;
5056  Datum newval;
5057 
5058  if (PG_ARGISNULL(0))
5059  {
5060  /* No non-null input seen so far... */
5061  if (PG_ARGISNULL(1))
5062  PG_RETURN_NULL(); /* still no non-null */
5063  /* This is the first non-null input. */
5065  PG_RETURN_DATUM(newval);
5066  }
5067 
5068  /*
5069  * Note that we cannot special-case the aggregate case here, as we do for
5070  * int2_sum and int4_sum: numeric is of variable size, so we cannot modify
5071  * our first parameter in-place.
5072  */
5073 
5074  oldsum = PG_GETARG_NUMERIC(0);
5075 
5076  /* Leave sum unchanged if new input is null. */
5077  if (PG_ARGISNULL(1))
5078  PG_RETURN_NUMERIC(oldsum);
5079 
5080  /* OK to do the addition. */
5082 
5084  NumericGetDatum(oldsum), newval));
5085 }
5086 
5087 
5088 /*
5089  * Routines for avg(int2) and avg(int4). The transition datatype
5090  * is a two-element int8 array, holding count and sum.
5091  *
5092  * These functions are also used for sum(int2) and sum(int4) when
5093  * operating in moving-aggregate mode, since for correct inverse transitions
5094  * we need to count the inputs.
5095  */
5096 
5097 typedef struct Int8TransTypeData
5098 {
5099  int64 count;
5100  int64 sum;
5102 
5103 Datum
5105 {
5106  ArrayType *transarray;
5107  int16 newval = PG_GETARG_INT16(1);
5108  Int8TransTypeData *transdata;
5109 
5110  /*
5111  * If we're invoked as an aggregate, we can cheat and modify our first
5112  * parameter in-place to reduce palloc overhead. Otherwise we need to make
5113  * a copy of it before scribbling on it.
5114  */
5115  if (AggCheckCallContext(fcinfo, NULL))
5116  transarray = PG_GETARG_ARRAYTYPE_P(0);
5117  else
5118  transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
5119 
5120  if (ARR_HASNULL(transarray) ||
5121  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
5122  elog(ERROR, "expected 2-element int8 array");
5123 
5124  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
5125  transdata->count++;
5126  transdata->sum += newval;
5127 
5128  PG_RETURN_ARRAYTYPE_P(transarray);
5129 }
5130 
5131 Datum
5133 {
5134  ArrayType *transarray;
5135  int32 newval = PG_GETARG_INT32(1);
5136  Int8TransTypeData *transdata;
5137 
5138  /*
5139  * If we're invoked as an aggregate, we can cheat and modify our first
5140  * parameter in-place to reduce palloc overhead. Otherwise we need to make
5141  * a copy of it before scribbling on it.
5142  */
5143  if (AggCheckCallContext(fcinfo, NULL))
5144  transarray = PG_GETARG_ARRAYTYPE_P(0);
5145  else
5146  transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
5147 
5148  if (ARR_HASNULL(transarray) ||
5149  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
5150  elog(ERROR, "expected 2-element int8 array");
5151 
5152  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
5153  transdata->count++;
5154  transdata->sum += newval;
5155 
5156  PG_RETURN_ARRAYTYPE_P(transarray);
5157 }
5158 
5159 Datum
5161 {
5162  ArrayType *transarray1;
5163  ArrayType *transarray2;
5164  Int8TransTypeData *state1;
5165  Int8TransTypeData *state2;
5166 
5167  if (!AggCheckCallContext(fcinfo, NULL))
5168  elog(ERROR, "aggregate function called in non-aggregate context");
5169 
5170  transarray1 = PG_GETARG_ARRAYTYPE_P(0);
5171  transarray2 = PG_GETARG_ARRAYTYPE_P(1);
5172 
5173  if (ARR_HASNULL(transarray1) ||
5174  ARR_SIZE(transarray1) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
5175  elog(ERROR, "expected 2-element int8 array");
5176 
5177  if (ARR_HASNULL(transarray2) ||
5178  ARR_SIZE(transarray2) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
5179  elog(ERROR, "expected 2-element int8 array");
5180 
5181  state1 = (Int8TransTypeData *) ARR_DATA_PTR(transarray1);
5182  state2 = (Int8TransTypeData *) ARR_DATA_PTR(transarray2);
5183 
5184  state1->count += state2->count;
5185  state1->sum += state2->sum;
5186 
5187  PG_RETURN_ARRAYTYPE_P(transarray1);
5188 }
5189 
5190 Datum
5192 {
5193  ArrayType *transarray;
5194  int16 newval = PG_GETARG_INT16(1);
5195  Int8TransTypeData *transdata;
5196 
5197  /*
5198  * If we're invoked as an aggregate, we can cheat and modify our first
5199  * parameter in-place to reduce palloc overhead. Otherwise we need to make
5200  * a copy of it before scribbling on it.
5201  */
5202  if (AggCheckCallContext(fcinfo, NULL))
5203  transarray = PG_GETARG_ARRAYTYPE_P(0);
5204  else
5205  transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
5206 
5207  if (ARR_HASNULL(transarray) ||
5208  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
5209  elog(ERROR, "expected 2-element int8 array");
5210 
5211  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
5212  transdata->count--;
5213  transdata->sum -= newval;
5214 
5215  PG_RETURN_ARRAYTYPE_P(transarray);
5216 }
5217 
5218 Datum
5220 {
5221  ArrayType *transarray;
5222  int32 newval = PG_GETARG_INT32(1);
5223  Int8TransTypeData *transdata;
5224 
5225  /*
5226  * If we're invoked as an aggregate, we can cheat and modify our first
5227  * parameter in-place to reduce palloc overhead. Otherwise we need to make
5228  * a copy of it before scribbling on it.
5229  */
5230  if (AggCheckCallContext(fcinfo, NULL))
5231  transarray = PG_GETARG_ARRAYTYPE_P(0);
5232  else
5233  transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
5234 
5235  if (ARR_HASNULL(transarray) ||
5236  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
5237  elog(ERROR, "expected 2-element int8 array");
5238 
5239  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
5240  transdata->count--;
5241  transdata->sum -= newval;
5242 
5243  PG_RETURN_ARRAYTYPE_P(transarray);
5244 }
5245 
5246 Datum
5248 {
5249  ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
5250  Int8TransTypeData *transdata;
5251  Datum countd,
5252  sumd;
5253 
5254  if (ARR_HASNULL(transarray) ||
5255  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
5256  elog(ERROR, "expected 2-element int8 array");
5257  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
5258 
5259  /* SQL defines AVG of no values to be NULL */
5260  if (transdata->count == 0)
5261  PG_RETURN_NULL();
5262 
5264  Int64GetDatumFast(transdata->count));
5266  Int64GetDatumFast(transdata->sum));
5267 
5269 }
5270 
5271 /*
5272  * SUM(int2) and SUM(int4) both return int8, so we can use this
5273  * final function for both.
5274  */
5275 Datum
5277 {
5278  ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
5279  Int8TransTypeData *transdata;
5280 
5281  if (ARR_HASNULL(transarray) ||
5282  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
5283  elog(ERROR, "expected 2-element int8 array");
5284  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
5285 
5286  /* SQL defines SUM of no values to be NULL */
5287  if (transdata->count == 0)
5288  PG_RETURN_NULL();
5289 
5290  PG_RETURN_DATUM(Int64GetDatumFast(transdata->sum));
5291 }
5292 
5293 
5294 /* ----------------------------------------------------------------------
5295  *
5296  * Debug support
5297  *
5298  * ----------------------------------------------------------------------
5299  */
5300 
5301 #ifdef NUMERIC_DEBUG
5302 
5303 /*
5304  * dump_numeric() - Dump a value in the db storage format for debugging
5305  */
5306 static void
5307 dump_numeric(const char *str, Numeric num)
5308 {
5310  int ndigits;
5311  int i;
5312 
5313  ndigits = NUMERIC_NDIGITS(num);
5314 
5315  printf("%s: NUMERIC w=%d d=%d ", str,
5316  NUMERIC_WEIGHT(num), NUMERIC_DSCALE(num));
5317  switch (NUMERIC_SIGN(num))
5318  {
5319  case NUMERIC_POS:
5320  printf("POS");
5321  break;
5322  case NUMERIC_NEG:
5323  printf("NEG");
5324  break;
5325  case NUMERIC_NAN:
5326  printf("NaN");
5327  break;
5328  default:
5329  printf("SIGN=0x%x", NUMERIC_SIGN(num));
5330  break;
5331  }
5332 
5333  for (i = 0; i < ndigits; i++)
5334  printf(" %0*d", DEC_DIGITS, digits[i]);
5335  printf("\n");
5336 }
5337 
5338 
5339 /*
5340  * dump_var() - Dump a value in the variable format for debugging
5341  */
5342 static void
5343 dump_var(const char *str, NumericVar *var)
5344 {
5345  int i;
5346 
5347  printf("%s: VAR w=%d d=%d ", str, var->weight, var->dscale);
5348  switch (var->sign)
5349  {
5350  case NUMERIC_POS:
5351  printf("POS");
5352  break;
5353  case NUMERIC_NEG:
5354  printf("NEG");
5355  break;
5356  case NUMERIC_NAN:
5357  printf("NaN");
5358  break;
5359  default:
5360  printf("SIGN=0x%x", var->sign);
5361  break;
5362  }
5363 
5364  for (i = 0; i < var->ndigits; i++)
5365  printf(" %0*d", DEC_DIGITS, var->digits[i]);
5366 
5367  printf("\n");
5368 }
5369 #endif /* NUMERIC_DEBUG */
5370 
5371 
5372 /* ----------------------------------------------------------------------
5373  *
5374  * Local functions follow
5375  *
5376  * In general, these do not support NaNs --- callers must eliminate
5377  * the possibility of NaN first. (make_result() is an exception.)
5378  *
5379  * ----------------------------------------------------------------------
5380  */
5381 
5382 
5383 /*
5384  * alloc_var() -
5385  *
5386  * Allocate a digit buffer of ndigits digits (plus a spare digit for rounding)
5387  */
5388 static void
5389 alloc_var(NumericVar *var, int ndigits)
5390 {
5391  digitbuf_free(var->buf);
5392  var->buf = digitbuf_alloc(ndigits + 1);
5393  var->buf[0] = 0; /* spare digit for rounding */
5394  var->digits = var->buf + 1;
5395  var->ndigits = ndigits;
5396 }
5397 
5398 
5399 /*
5400  * free_var() -
5401  *
5402  * Return the digit buffer of a variable to the free pool
5403  */
5404 static void
5406 {
5407  digitbuf_free(var->buf);
5408  var->buf = NULL;
5409  var->digits = NULL;
5410  var->sign = NUMERIC_NAN;
5411 }
5412 
5413 
5414 /*
5415  * zero_var() -
5416  *
5417  * Set a variable to ZERO.
5418  * Note: its dscale is not touched.
5419  */
5420 static void
5422 {
5423  digitbuf_free(var->buf);
5424  var->buf = NULL;
5425  var->digits = NULL;
5426  var->ndigits = 0;
5427  var->weight = 0; /* by convention; doesn't really matter */
5428  var->sign = NUMERIC_POS; /* anything but NAN... */
5429 }
5430 
5431 
5432 /*
5433  * set_var_from_str()
5434  *
5435  * Parse a string and put the number into a variable
5436  *
5437  * This function does not handle leading or trailing spaces, and it doesn't
5438  * accept "NaN" either. It returns the end+1 position so that caller can
5439  * check for trailing spaces/garbage if deemed necessary.
5440  *
5441  * cp is the place to actually start parsing; str is what to use in error
5442  * reports. (Typically cp would be the same except advanced over spaces.)
5443  */
5444 static const char *
5445 set_var_from_str(const char *str, const char *cp, NumericVar *dest)
5446 {
5447  bool have_dp = FALSE;
5448  int i;
5449  unsigned char *decdigits;
5450  int sign = NUMERIC_POS;
5451  int dweight = -1;
5452  int ddigits;
5453  int dscale = 0;
5454  int weight;
5455  int ndigits;
5456  int offset;
5458 
5459  /*
5460  * We first parse the string to extract decimal digits and determine the
5461  * correct decimal weight. Then convert to NBASE representation.
5462  */
5463  switch (*cp)
5464  {
5465  case '+':
5466  sign = NUMERIC_POS;
5467  cp++;
5468  break;
5469 
5470  case '-':
5471  sign = NUMERIC_NEG;
5472  cp++;
5473  break;
5474  }
5475 
5476  if (*cp == '.')
5477  {
5478  have_dp = TRUE;
5479  cp++;
5480  }
5481 
5482  if (!isdigit((unsigned char) *cp))
5483  ereport(ERROR,
5484  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
5485  errmsg("invalid input syntax for type %s: \"%s\"",
5486  "numeric", str)));
5487 
5488  decdigits = (unsigned char *) palloc(strlen(cp) + DEC_DIGITS * 2);
5489 
5490  /* leading padding for digit alignment later */
5491  memset(decdigits, 0, DEC_DIGITS);
5492  i = DEC_DIGITS;
5493 
5494  while (*cp)
5495  {
5496  if (isdigit((unsigned char) *cp))
5497  {
5498  decdigits[i++] = *cp++ - '0';
5499  if (!have_dp)
5500  dweight++;
5501  else
5502  dscale++;
5503  }
5504  else if (*cp == '.')
5505  {
5506  if (have_dp)
5507  ereport(ERROR,
5508  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
5509  errmsg("invalid input syntax for type %s: \"%s\"",
5510  "numeric", str)));
5511  have_dp = TRUE;
5512  cp++;
5513  }
5514  else
5515  break;
5516  }
5517 
5518  ddigits = i - DEC_DIGITS;
5519  /* trailing padding for digit alignment later */
5520  memset(decdigits + i, 0, DEC_DIGITS - 1);
5521 
5522  /* Handle exponent, if any */
5523  if (*cp == 'e' || *cp == 'E')
5524  {
5525  long exponent;
5526  char *endptr;
5527 
5528  cp++;
5529  exponent = strtol(cp, &endptr, 10);
5530  if (endptr == cp)
5531  ereport(ERROR,
5532  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
5533  errmsg("invalid input syntax for type %s: \"%s\"",
5534  "numeric", str)));
5535  cp = endptr;
5536 
5537  /*
5538  * At this point, dweight and dscale can't be more than about
5539  * INT_MAX/2 due to the MaxAllocSize limit on string length, so
5540  * constraining the exponent similarly should be enough to prevent
5541  * integer overflow in this function. If the value is too large to
5542  * fit in storage format, make_result() will complain about it later;
5543  * for consistency use the same ereport errcode/text as make_result().
5544  */
5545  if (exponent >= INT_MAX / 2 || exponent <= -(INT_MAX / 2))
5546  ereport(ERROR,
5547  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
5548  errmsg("value overflows numeric format")));
5549  dweight += (int) exponent;
5550  dscale -= (int) exponent;
5551  if (dscale < 0)
5552  dscale = 0;
5553  }
5554 
5555  /*
5556  * Okay, convert pure-decimal representation to base NBASE. First we need
5557  * to determine the converted weight and ndigits. offset is the number of
5558  * decimal zeroes to insert before the first given digit to have a
5559  * correctly aligned first NBASE digit.
5560  */
5561  if (dweight >= 0)
5562  weight = (dweight + 1 + DEC_DIGITS - 1) / DEC_DIGITS - 1;
5563  else
5564  weight = -((-dweight - 1) / DEC_DIGITS + 1);
5565  offset = (weight + 1) * DEC_DIGITS - (dweight + 1);
5566  ndigits = (ddigits + offset + DEC_DIGITS - 1) / DEC_DIGITS;
5567 
5568  alloc_var(dest, ndigits);
5569  dest->sign = sign;
5570  dest->weight = weight;
5571  dest->dscale = dscale;
5572 
5573  i = DEC_DIGITS - offset;
5574  digits = dest->digits;
5575 
5576  while (ndigits-- > 0)
5577  {
5578 #if DEC_DIGITS == 4
5579  *digits++ = ((decdigits[i] * 10 + decdigits[i + 1]) * 10 +
5580  decdigits[i + 2]) * 10 + decdigits[i + 3];
5581 #elif DEC_DIGITS == 2
5582  *digits++ = decdigits[i] * 10 + decdigits[i + 1];
5583 #elif DEC_DIGITS == 1
5584  *digits++ = decdigits[i];
5585 #else
5586 #error unsupported NBASE
5587 #endif
5588  i += DEC_DIGITS;
5589  }
5590 
5591  pfree(decdigits);
5592 
5593  /* Strip any leading/trailing zeroes, and normalize weight if zero */
5594  strip_var(dest);
5595 
5596  /* Return end+1 position for caller */
5597  return cp;
5598 }
5599 
5600 
5601 /*
5602  * set_var_from_num() -
5603  *
5604  * Convert the packed db format into a variable
5605  */
5606 static void
5608 {
5609  int ndigits;
5610 
5611  ndigits = NUMERIC_NDIGITS(num);
5612 
5613  alloc_var(dest, ndigits);
5614 
5615  dest->weight = NUMERIC_WEIGHT(num);
5616  dest->sign = NUMERIC_SIGN(num);
5617  dest->dscale = NUMERIC_DSCALE(num);
5618 
5619  memcpy(dest->digits, NUMERIC_DIGITS(num), ndigits * sizeof(NumericDigit));
5620 }
5621 
5622 
5623 /*
5624  * init_var_from_num() -
5625  *
5626  * Initialize a variable from packed db format. The digits array is not
5627  * copied, which saves some cycles when the resulting var is not modified.
5628  * Also, there's no need to call free_var(), as long as you don't assign any
5629  * other value to it (with set_var_* functions, or by using the var as the
5630  * destination of a function like add_var())
5631  *
5632  * CAUTION: Do not modify the digits buffer of a var initialized with this
5633  * function, e.g by calling round_var() or trunc_var(), as the changes will
5634  * propagate to the original Numeric! It's OK to use it as the destination
5635  * argument of one of the calculational functions, though.
5636  */
5637 static void
5639 {
5640  dest->ndigits = NUMERIC_NDIGITS(num);
5641  dest->weight = NUMERIC_WEIGHT(num);
5642  dest->sign = NUMERIC_SIGN(num);
5643  dest->dscale = NUMERIC_DSCALE(num);
5644  dest->digits = NUMERIC_DIGITS(num);
5645  dest->buf = NULL; /* digits array is not palloc'd */
5646 }
5647 
5648 
5649 /*
5650  * set_var_from_var() -
5651  *
5652  * Copy one variable into another
5653  */
5654 static void
5656 {
5657  NumericDigit *newbuf;
5658 
5659  newbuf = digitbuf_alloc(value->ndigits + 1);
5660  newbuf[0] = 0; /* spare digit for rounding */
5661  if (value->ndigits > 0) /* else value->digits might be null */
5662  memcpy(newbuf + 1, value->digits,
5663  value->ndigits * sizeof(NumericDigit));
5664 
5665  digitbuf_free(dest->buf);
5666 
5667  memmove(dest, value, sizeof(NumericVar));
5668  dest->buf = newbuf;
5669  dest->digits = newbuf + 1;
5670 }
5671 
5672 
5673 /*
5674  * get_str_from_var() -
5675  *
5676  * Convert a var to text representation (guts of numeric_out).
5677  * The var is displayed to the number of digits indicated by its dscale.
5678  * Returns a palloc'd string.
5679  */
5680 static char *
5682 {
5683  int dscale;
5684  char *str;
5685  char *cp;
5686  char *endcp;
5687  int i;
5688  int d;
5689  NumericDigit dig;
5690 
5691 #if DEC_DIGITS > 1
5692  NumericDigit d1;
5693 #endif
5694 
5695  dscale = var->dscale;
5696 
5697  /*
5698  * Allocate space for the result.
5699  *
5700  * i is set to the # of decimal digits before decimal point. dscale is the
5701  * # of decimal digits we will print after decimal point. We may generate
5702  * as many as DEC_DIGITS-1 excess digits at the end, and in addition we
5703  * need room for sign, decimal point, null terminator.
5704  */
5705  i = (var->weight + 1) * DEC_DIGITS;
5706  if (i <= 0)
5707  i = 1;
5708 
5709  str = palloc(i + dscale + DEC_DIGITS + 2);
5710  cp = str;
5711 
5712  /*
5713  * Output a dash for negative values
5714  */
5715  if (var->sign == NUMERIC_NEG)
5716  *cp++ = '-';
5717 
5718  /*
5719  * Output all digits before the decimal point
5720  */
5721  if (var->weight < 0)
5722  {
5723  d = var->weight + 1;
5724  *cp++ = '0';
5725  }
5726  else
5727  {
5728  for (d = 0; d <= var->weight; d++)
5729  {
5730  dig = (d < var->ndigits) ? var->digits[d] : 0;
5731  /* In the first digit, suppress extra leading decimal zeroes */
5732 #if DEC_DIGITS == 4
5733  {
5734  bool putit = (d > 0);
5735 
5736  d1 = dig / 1000;
5737  dig -= d1 * 1000;
5738  putit |= (d1 > 0);
5739  if (putit)
5740  *cp++ = d1 + '0';
5741  d1 = dig / 100;
5742  dig -= d1 * 100;
5743  putit |= (d1 > 0);
5744  if (putit)
5745  *cp++ = d1 + '0';
5746  d1 = dig / 10;
5747  dig -= d1 * 10;
5748  putit |= (d1 > 0);
5749  if (putit)
5750  *cp++ = d1 + '0';
5751  *cp++ = dig + '0';
5752  }
5753 #elif DEC_DIGITS == 2
5754  d1 = dig / 10;
5755  dig -= d1 * 10;
5756  if (d1 > 0 || d > 0)
5757  *cp++ = d1 + '0';
5758  *cp++ = dig + '0';
5759 #elif DEC_DIGITS == 1
5760  *cp++ = dig + '0';
5761 #else
5762 #error unsupported NBASE
5763 #endif
5764  }
5765  }
5766 
5767  /*
5768  * If requested, output a decimal point and all the digits that follow it.
5769  * We initially put out a multiple of DEC_DIGITS digits, then truncate if
5770  * needed.
5771  */
5772  if (dscale > 0)
5773  {
5774  *cp++ = '.';
5775  endcp = cp + dscale;
5776  for (i = 0; i < dscale; d++, i += DEC_DIGITS)
5777  {
5778  dig = (d >= 0 && d < var->ndigits) ? var->digits[d] : 0;
5779 #if DEC_DIGITS == 4
5780  d1 = dig / 1000;
5781  dig -= d1 * 1000;
5782  *cp++ = d1 + '0';
5783  d1 = dig / 100;
5784  dig -= d1 * 100;
5785  *cp++ = d1 + '0';
5786  d1 = dig / 10;
5787  dig -= d1 * 10;
5788  *cp++ = d1 + '0';
5789  *cp++ = dig + '0';
5790 #elif DEC_DIGITS == 2
5791  d1 = dig / 10;
5792  dig -= d1 * 10;
5793  *cp++ = d1 + '0';
5794  *cp++ = dig + '0';
5795 #elif DEC_DIGITS == 1
5796  *cp++ = dig + '0';
5797 #else
5798 #error unsupported NBASE
5799 #endif
5800  }
5801  cp = endcp;
5802  }
5803 
5804  /*
5805  * terminate the string and return it
5806  */
5807  *cp = '\0';
5808  return str;
5809 }
5810 
5811 /*
5812  * get_str_from_var_sci() -
5813  *
5814  * Convert a var to a normalised scientific notation text representation.
5815  * This function does the heavy lifting for numeric_out_sci().
5816  *
5817  * This notation has the general form a * 10^b, where a is known as the
5818  * "significand" and b is known as the "exponent".
5819  *
5820  * Because we can't do superscript in ASCII (and because we want to copy
5821  * printf's behaviour) we display the exponent using E notation, with a
5822  * minimum of two exponent digits.
5823  *
5824  * For example, the value 1234 could be output as 1.2e+03.
5825  *
5826  * We assume that the exponent can fit into an int32.
5827  *
5828  * rscale is the number of decimal digits desired after the decimal point in
5829  * the output, negative values will be treated as meaning zero.
5830  *
5831  * Returns a palloc'd string.
5832  */
5833 static char *
5835 {
5836  int32 exponent;
5837  NumericVar denominator;
5838  NumericVar significand;
5839  int denom_scale;
5840  size_t len;
5841  char *str;
5842  char *sig_out;
5843 
5844  if (rscale < 0)
5845  rscale = 0;
5846 
5847  /*
5848  * Determine the exponent of this number in normalised form.
5849  *
5850  * This is the exponent required to represent the number with only one
5851  * significant digit before the decimal place.
5852  */
5853  if (var->ndigits > 0)
5854  {
5855  exponent = (var->weight + 1) * DEC_DIGITS;
5856 
5857  /*
5858  * Compensate for leading decimal zeroes in the first numeric digit by
5859  * decrementing the exponent.
5860  */
5861  exponent -= DEC_DIGITS - (int) log10(var->digits[0]);
5862  }
5863  else
5864  {
5865  /*
5866  * If var has no digits, then it must be zero.
5867  *
5868  * Zero doesn't technically have a meaningful exponent in normalised
5869  * notation, but we just display the exponent as zero for consistency
5870  * of output.
5871  */
5872  exponent = 0;
5873  }
5874 
5875  /*
5876  * The denominator is set to 10 raised to the power of the exponent.
5877  *
5878  * We then divide var by the denominator to get the significand, rounding
5879  * to rscale decimal digits in the process.
5880  */
5881  if (exponent < 0)
5882  denom_scale = -exponent;
5883  else
5884  denom_scale = 0;
5885 
5886  init_var(&denominator);
5887  init_var(&significand);
5888 
5889  power_var_int(&const_ten, exponent, &denominator, denom_scale);
5890  div_var(var, &denominator, &significand, rscale, true);
5891  sig_out = get_str_from_var(&significand);
5892 
5893  free_var(&denominator);
5894  free_var(&significand);
5895 
5896  /*
5897  * Allocate space for the result.
5898  *
5899  * In addition to the significand, we need room for the exponent
5900  * decoration ("e"), the sign of the exponent, up to 10 digits for the
5901  * exponent itself, and of course the null terminator.
5902  */
5903  len = strlen(sig_out) + 13;
5904  str = palloc(len);
5905  snprintf(str, len, "%se%+03d", sig_out, exponent);
5906 
5907  pfree(sig_out);
5908 
5909  return str;
5910 }
5911 
5912 
5913 /*
5914  * make_result() -
5915  *
5916  * Create the packed db numeric format in palloc()'d memory from
5917  * a variable.
5918  */
5919 static Numeric
5921 {
5922  Numeric result;
5923  NumericDigit *digits = var->digits;
5924  int weight = var->weight;
5925  int sign = var->sign;
5926  int n;
5927  Size len;
5928 
5929  if (sign == NUMERIC_NAN)
5930  {
5931  result = (Numeric) palloc(NUMERIC_HDRSZ_SHORT);