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