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