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