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