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