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