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