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