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