1 /*-------------------------------------------------------------------------
4 * Ordered-set aggregate functions.
6 * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/utils/adt/orderedsetaggs.c
13 *-------------------------------------------------------------------------
19 #include "catalog/pg_aggregate.h"
20 #include "catalog/pg_operator.h"
21 #include "catalog/pg_type.h"
22 #include "executor/executor.h"
23 #include "miscadmin.h"
24 #include "nodes/nodeFuncs.h"
25 #include "optimizer/optimizer.h"
26 #include "utils/array.h"
27 #include "utils/builtins.h"
28 #include "utils/lsyscache.h"
29 #include "utils/memutils.h"
30 #include "utils/timestamp.h"
31 #include "utils/tuplesort.h"
35 * Generic support for ordered-set aggregates
37 * The state for an ordered-set aggregate is divided into a per-group struct
38 * (which is the internal-type transition state datum returned to nodeAgg.c)
39 * and a per-query struct, which contains data and sub-objects that we can
40 * create just once per query because they will not change across groups.
41 * The per-query struct and subsidiary data live in the executor's per-query
42 * memory context, and go away implicitly at ExecutorEnd().
44 * These structs are set up during the first call of the transition function.
45 * Because we allow nodeAgg.c to merge ordered-set aggregates (but not
46 * hypothetical aggregates) with identical inputs and transition functions,
47 * this info must not depend on the particular aggregate (ie, particular
48 * final-function), nor on the direct argument(s) of the aggregate.
51 typedef struct OSAPerQueryState
53 /* Representative Aggref for this aggregate: */
55 /* Memory context containing this struct and other per-query data: */
56 MemoryContext qcontext;
57 /* Context for expression evaluation */
58 ExprContext *econtext;
59 /* Do we expect multiple final-function calls within one group? */
62 /* These fields are used only when accumulating tuples: */
64 /* Tuple descriptor for tuples inserted into sortstate: */
66 /* Tuple slot we can use for inserting/extracting tuples: */
67 TupleTableSlot *tupslot;
68 /* Per-sort-column sorting information */
70 AttrNumber *sortColIdx;
74 bool *sortNullsFirsts;
75 /* Equality operator call info, created only if needed: */
76 ExprState *compareTuple;
78 /* These fields are used only when accumulating datums: */
80 /* Info about datatype of datums being sorted: */
85 /* Info about sort ordering: */
90 /* Equality operator call info, created only if needed: */
94 typedef struct OSAPerGroupState
96 /* Link to the per-query state for this aggregate: */
97 OSAPerQueryState *qstate;
98 /* Memory context containing per-group data: */
99 MemoryContext gcontext;
100 /* Sort object we're accumulating data in: */
101 Tuplesortstate *sortstate;
102 /* Number of normal rows inserted into sortstate: */
103 int64 number_of_rows;
104 /* Have we already done tuplesort_performsort? */
108 static void ordered_set_shutdown(Datum arg);
112 * Set up working state for an ordered-set aggregate
114 static OSAPerGroupState *
115 ordered_set_startup(FunctionCallInfo fcinfo, bool use_tuples)
117 OSAPerGroupState *osastate;
118 OSAPerQueryState *qstate;
119 MemoryContext gcontext;
120 MemoryContext oldcontext;
123 * Check we're called as aggregate (and not a window function), and get
124 * the Agg node's group-lifespan context (which might change from group to
125 * group, so we shouldn't cache it in the per-query state).
127 if (AggCheckCallContext(fcinfo, &gcontext) != AGG_CONTEXT_AGGREGATE)
128 elog(ERROR, "ordered-set aggregate called in non-aggregate context");
131 * We keep a link to the per-query state in fn_extra; if it's not there,
132 * create it, and do the per-query setup we need.
134 qstate = (OSAPerQueryState *) fcinfo->flinfo->fn_extra;
138 MemoryContext qcontext;
142 /* Get the Aggref so we can examine aggregate's arguments */
143 aggref = AggGetAggref(fcinfo);
145 elog(ERROR, "ordered-set aggregate called in non-aggregate context");
146 if (!AGGKIND_IS_ORDERED_SET(aggref->aggkind))
147 elog(ERROR, "ordered-set aggregate support function called for non-ordered-set aggregate");
150 * Prepare per-query structures in the fn_mcxt, which we assume is the
151 * executor's per-query context; in any case it's the right place to
152 * keep anything found via fn_extra.
154 qcontext = fcinfo->flinfo->fn_mcxt;
155 oldcontext = MemoryContextSwitchTo(qcontext);
157 qstate = (OSAPerQueryState *) palloc0(sizeof(OSAPerQueryState));
158 qstate->aggref = aggref;
159 qstate->qcontext = qcontext;
161 /* We need to support rescans if the trans state is shared */
162 qstate->rescan_needed = AggStateIsShared(fcinfo);
164 /* Extract the sort information */
165 sortlist = aggref->aggorder;
166 numSortCols = list_length(sortlist);
170 bool ishypothetical = (aggref->aggkind == AGGKIND_HYPOTHETICAL);
175 numSortCols++; /* make space for flag column */
176 qstate->numSortCols = numSortCols;
177 qstate->sortColIdx = (AttrNumber *) palloc(numSortCols * sizeof(AttrNumber));
178 qstate->sortOperators = (Oid *) palloc(numSortCols * sizeof(Oid));
179 qstate->eqOperators = (Oid *) palloc(numSortCols * sizeof(Oid));
180 qstate->sortCollations = (Oid *) palloc(numSortCols * sizeof(Oid));
181 qstate->sortNullsFirsts = (bool *) palloc(numSortCols * sizeof(bool));
184 foreach(lc, sortlist)
186 SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc);
187 TargetEntry *tle = get_sortgroupclause_tle(sortcl,
190 /* the parser should have made sure of this */
191 Assert(OidIsValid(sortcl->sortop));
193 qstate->sortColIdx[i] = tle->resno;
194 qstate->sortOperators[i] = sortcl->sortop;
195 qstate->eqOperators[i] = sortcl->eqop;
196 qstate->sortCollations[i] = exprCollation((Node *) tle->expr);
197 qstate->sortNullsFirsts[i] = sortcl->nulls_first;
203 /* Add an integer flag column as the last sort column */
204 qstate->sortColIdx[i] = list_length(aggref->args) + 1;
205 qstate->sortOperators[i] = Int4LessOperator;
206 qstate->eqOperators[i] = Int4EqualOperator;
207 qstate->sortCollations[i] = InvalidOid;
208 qstate->sortNullsFirsts[i] = false;
212 Assert(i == numSortCols);
215 * Get a tupledesc corresponding to the aggregated inputs
216 * (including sort expressions) of the agg.
218 qstate->tupdesc = ExecTypeFromTL(aggref->args);
220 /* If we need a flag column, hack the tupledesc to include that */
224 int natts = qstate->tupdesc->natts;
226 newdesc = CreateTemplateTupleDesc(natts + 1);
227 for (i = 1; i <= natts; i++)
228 TupleDescCopyEntry(newdesc, i, qstate->tupdesc, i);
230 TupleDescInitEntry(newdesc,
231 (AttrNumber) ++natts,
237 FreeTupleDesc(qstate->tupdesc);
238 qstate->tupdesc = newdesc;
241 /* Create slot we'll use to store/retrieve rows */
242 qstate->tupslot = MakeSingleTupleTableSlot(qstate->tupdesc,
243 &TTSOpsMinimalTuple);
247 /* Sort single datums */
248 SortGroupClause *sortcl;
251 if (numSortCols != 1 || aggref->aggkind == AGGKIND_HYPOTHETICAL)
252 elog(ERROR, "ordered-set aggregate support function does not support multiple aggregated columns");
254 sortcl = (SortGroupClause *) linitial(sortlist);
255 tle = get_sortgroupclause_tle(sortcl, aggref->args);
257 /* the parser should have made sure of this */
258 Assert(OidIsValid(sortcl->sortop));
260 /* Save sort ordering info */
261 qstate->sortColType = exprType((Node *) tle->expr);
262 qstate->sortOperator = sortcl->sortop;
263 qstate->eqOperator = sortcl->eqop;
264 qstate->sortCollation = exprCollation((Node *) tle->expr);
265 qstate->sortNullsFirst = sortcl->nulls_first;
267 /* Save datatype info */
268 get_typlenbyvalalign(qstate->sortColType,
274 fcinfo->flinfo->fn_extra = (void *) qstate;
276 MemoryContextSwitchTo(oldcontext);
279 /* Now build the stuff we need in group-lifespan context */
280 oldcontext = MemoryContextSwitchTo(gcontext);
282 osastate = (OSAPerGroupState *) palloc(sizeof(OSAPerGroupState));
283 osastate->qstate = qstate;
284 osastate->gcontext = gcontext;
287 * Initialize tuplesort object.
290 osastate->sortstate = tuplesort_begin_heap(qstate->tupdesc,
293 qstate->sortOperators,
294 qstate->sortCollations,
295 qstate->sortNullsFirsts,
298 qstate->rescan_needed);
300 osastate->sortstate = tuplesort_begin_datum(qstate->sortColType,
301 qstate->sortOperator,
302 qstate->sortCollation,
303 qstate->sortNullsFirst,
306 qstate->rescan_needed);
308 osastate->number_of_rows = 0;
309 osastate->sort_done = false;
311 /* Now register a shutdown callback to clean things up at end of group */
312 AggRegisterCallback(fcinfo,
313 ordered_set_shutdown,
314 PointerGetDatum(osastate));
316 MemoryContextSwitchTo(oldcontext);
322 * Clean up when evaluation of an ordered-set aggregate is complete.
324 * We don't need to bother freeing objects in the per-group memory context,
325 * since that will get reset anyway by nodeAgg.c; nor should we free anything
326 * in the per-query context, which will get cleared (if this was the last
327 * group) by ExecutorEnd. But we must take care to release any potential
328 * non-memory resources.
330 * In the case where we're not expecting multiple finalfn calls, we could
331 * arguably rely on the finalfn to clean up; but it's easier and more testable
332 * if we just do it the same way in either case.
335 ordered_set_shutdown(Datum arg)
337 OSAPerGroupState *osastate = (OSAPerGroupState *) DatumGetPointer(arg);
339 /* Tuplesort object might have temp files. */
340 if (osastate->sortstate)
341 tuplesort_end(osastate->sortstate);
342 osastate->sortstate = NULL;
343 /* The tupleslot probably can't be holding a pin, but let's be safe. */
344 if (osastate->qstate->tupslot)
345 ExecClearTuple(osastate->qstate->tupslot);
350 * Generic transition function for ordered-set aggregates
351 * with a single input column in which we want to suppress nulls
354 ordered_set_transition(PG_FUNCTION_ARGS)
356 OSAPerGroupState *osastate;
358 /* If first call, create the transition state workspace */
360 osastate = ordered_set_startup(fcinfo, false);
362 osastate = (OSAPerGroupState *) PG_GETARG_POINTER(0);
364 /* Load the datum into the tuplesort object, but only if it's not null */
365 if (!PG_ARGISNULL(1))
367 tuplesort_putdatum(osastate->sortstate, PG_GETARG_DATUM(1), false);
368 osastate->number_of_rows++;
371 PG_RETURN_POINTER(osastate);
375 * Generic transition function for ordered-set aggregates
376 * with (potentially) multiple aggregated input columns
379 ordered_set_transition_multi(PG_FUNCTION_ARGS)
381 OSAPerGroupState *osastate;
382 TupleTableSlot *slot;
386 /* If first call, create the transition state workspace */
388 osastate = ordered_set_startup(fcinfo, true);
390 osastate = (OSAPerGroupState *) PG_GETARG_POINTER(0);
392 /* Form a tuple from all the other inputs besides the transition value */
393 slot = osastate->qstate->tupslot;
394 ExecClearTuple(slot);
395 nargs = PG_NARGS() - 1;
396 for (i = 0; i < nargs; i++)
398 slot->tts_values[i] = PG_GETARG_DATUM(i + 1);
399 slot->tts_isnull[i] = PG_ARGISNULL(i + 1);
401 if (osastate->qstate->aggref->aggkind == AGGKIND_HYPOTHETICAL)
403 /* Add a zero flag value to mark this row as a normal input row */
404 slot->tts_values[i] = Int32GetDatum(0);
405 slot->tts_isnull[i] = false;
408 Assert(i == slot->tts_tupleDescriptor->natts);
409 ExecStoreVirtualTuple(slot);
411 /* Load the row into the tuplesort object */
412 tuplesort_puttupleslot(osastate->sortstate, slot);
413 osastate->number_of_rows++;
415 PG_RETURN_POINTER(osastate);
420 * percentile_disc(float8) within group(anyelement) - discrete percentile
423 percentile_disc_final(PG_FUNCTION_ARGS)
425 OSAPerGroupState *osastate;
431 Assert(AggCheckCallContext(fcinfo, NULL) == AGG_CONTEXT_AGGREGATE);
433 /* Get and check the percentile argument */
437 percentile = PG_GETARG_FLOAT8(1);
439 if (percentile < 0 || percentile > 1 || isnan(percentile))
441 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
442 errmsg("percentile value %g is not between 0 and 1",
445 /* If there were no regular rows, the result is NULL */
449 osastate = (OSAPerGroupState *) PG_GETARG_POINTER(0);
451 /* number_of_rows could be zero if we only saw NULL input values */
452 if (osastate->number_of_rows == 0)
455 /* Finish the sort, or rescan if we already did */
456 if (!osastate->sort_done)
458 tuplesort_performsort(osastate->sortstate);
459 osastate->sort_done = true;
462 tuplesort_rescan(osastate->sortstate);
465 * We need the smallest K such that (K/N) >= percentile.
466 * N>0, therefore K >= N*percentile, therefore K = ceil(N*percentile).
467 * So we skip K-1 rows (if K>0) and return the next row fetched.
470 rownum = (int64) ceil(percentile * osastate->number_of_rows);
471 Assert(rownum <= osastate->number_of_rows);
475 if (!tuplesort_skiptuples(osastate->sortstate, rownum - 1, true))
476 elog(ERROR, "missing row in percentile_disc");
479 if (!tuplesort_getdatum(osastate->sortstate, true, &val, &isnull, NULL))
480 elog(ERROR, "missing row in percentile_disc");
482 /* We shouldn't have stored any nulls, but do the right thing anyway */
486 PG_RETURN_DATUM(val);
491 * For percentile_cont, we need a way to interpolate between consecutive
492 * values. Use a helper function for that, so that we can share the rest
493 * of the code between types.
495 typedef Datum (*LerpFunc) (Datum lo, Datum hi, double pct);
498 float8_lerp(Datum lo, Datum hi, double pct)
500 double loval = DatumGetFloat8(lo);
501 double hival = DatumGetFloat8(hi);
503 return Float8GetDatum(loval + (pct * (hival - loval)));
507 interval_lerp(Datum lo, Datum hi, double pct)
509 Datum diff_result = DirectFunctionCall2(interval_mi, hi, lo);
510 Datum mul_result = DirectFunctionCall2(interval_mul,
512 Float8GetDatumFast(pct));
514 return DirectFunctionCall2(interval_pl, mul_result, lo);
518 * Continuous percentile
521 percentile_cont_final_common(FunctionCallInfo fcinfo,
525 OSAPerGroupState *osastate;
528 int64 second_row = 0;
535 Assert(AggCheckCallContext(fcinfo, NULL) == AGG_CONTEXT_AGGREGATE);
537 /* Get and check the percentile argument */
541 percentile = PG_GETARG_FLOAT8(1);
543 if (percentile < 0 || percentile > 1 || isnan(percentile))
545 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
546 errmsg("percentile value %g is not between 0 and 1",
549 /* If there were no regular rows, the result is NULL */
553 osastate = (OSAPerGroupState *) PG_GETARG_POINTER(0);
555 /* number_of_rows could be zero if we only saw NULL input values */
556 if (osastate->number_of_rows == 0)
559 Assert(expect_type == osastate->qstate->sortColType);
561 /* Finish the sort, or rescan if we already did */
562 if (!osastate->sort_done)
564 tuplesort_performsort(osastate->sortstate);
565 osastate->sort_done = true;
568 tuplesort_rescan(osastate->sortstate);
570 first_row = floor(percentile * (osastate->number_of_rows - 1));
571 second_row = ceil(percentile * (osastate->number_of_rows - 1));
573 Assert(first_row < osastate->number_of_rows);
575 if (!tuplesort_skiptuples(osastate->sortstate, first_row, true))
576 elog(ERROR, "missing row in percentile_cont");
578 if (!tuplesort_getdatum(osastate->sortstate, true, &first_val, &isnull, NULL))
579 elog(ERROR, "missing row in percentile_cont");
583 if (first_row == second_row)
589 if (!tuplesort_getdatum(osastate->sortstate, true, &second_val, &isnull, NULL))
590 elog(ERROR, "missing row in percentile_cont");
595 proportion = (percentile * (osastate->number_of_rows - 1)) - first_row;
596 val = lerpfunc(first_val, second_val, proportion);
599 PG_RETURN_DATUM(val);
603 * percentile_cont(float8) within group (float8) - continuous percentile
606 percentile_cont_float8_final(PG_FUNCTION_ARGS)
608 return percentile_cont_final_common(fcinfo, FLOAT8OID, float8_lerp);
612 * percentile_cont(float8) within group (interval) - continuous percentile
615 percentile_cont_interval_final(PG_FUNCTION_ARGS)
617 return percentile_cont_final_common(fcinfo, INTERVALOID, interval_lerp);
622 * Support code for handling arrays of percentiles
624 * Note: in each pct_info entry, second_row should be equal to or
625 * exactly one more than first_row.
629 int64 first_row; /* first row to sample */
630 int64 second_row; /* possible second row to sample */
631 double proportion; /* interpolation fraction */
632 int idx; /* index of this item in original array */
636 * Sort comparator to sort pct_infos by first_row then second_row
639 pct_info_cmp(const void *pa, const void *pb)
641 const struct pct_info *a = (const struct pct_info *) pa;
642 const struct pct_info *b = (const struct pct_info *) pb;
644 if (a->first_row != b->first_row)
645 return (a->first_row < b->first_row) ? -1 : 1;
646 if (a->second_row != b->second_row)
647 return (a->second_row < b->second_row) ? -1 : 1;
652 * Construct array showing which rows to sample for percentiles.
654 static struct pct_info *
655 setup_pct_info(int num_percentiles,
656 Datum *percentiles_datum,
657 bool *percentiles_null,
661 struct pct_info *pct_info;
664 pct_info = (struct pct_info *) palloc(num_percentiles * sizeof(struct pct_info));
666 for (i = 0; i < num_percentiles; i++)
670 if (percentiles_null[i])
672 /* dummy entry for any NULL in array */
673 pct_info[i].first_row = 0;
674 pct_info[i].second_row = 0;
675 pct_info[i].proportion = 0;
679 double p = DatumGetFloat8(percentiles_datum[i]);
681 if (p < 0 || p > 1 || isnan(p))
683 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
684 errmsg("percentile value %g is not between 0 and 1",
689 pct_info[i].first_row = 1 + floor(p * (rowcount - 1));
690 pct_info[i].second_row = 1 + ceil(p * (rowcount - 1));
691 pct_info[i].proportion = (p * (rowcount - 1)) - floor(p * (rowcount - 1));
696 * We need the smallest K such that (K/N) >= percentile.
697 * N>0, therefore K >= N*percentile, therefore
698 * K = ceil(N*percentile); but not less than 1.
701 int64 row = (int64) ceil(p * rowcount);
704 pct_info[i].first_row = row;
705 pct_info[i].second_row = row;
706 pct_info[i].proportion = 0;
712 * The parameter array wasn't necessarily in sorted order, but we need to
713 * visit the rows in order, so sort by first_row/second_row.
715 qsort(pct_info, num_percentiles, sizeof(struct pct_info), pct_info_cmp);
721 * percentile_disc(float8[]) within group (anyelement) - discrete percentiles
724 percentile_disc_multi_final(PG_FUNCTION_ARGS)
726 OSAPerGroupState *osastate;
728 Datum *percentiles_datum;
729 bool *percentiles_null;
731 struct pct_info *pct_info;
735 Datum val = (Datum) 0;
739 Assert(AggCheckCallContext(fcinfo, NULL) == AGG_CONTEXT_AGGREGATE);
741 /* If there were no regular rows, the result is NULL */
745 osastate = (OSAPerGroupState *) PG_GETARG_POINTER(0);
747 /* number_of_rows could be zero if we only saw NULL input values */
748 if (osastate->number_of_rows == 0)
751 /* Deconstruct the percentile-array input */
754 param = PG_GETARG_ARRAYTYPE_P(1);
756 deconstruct_array(param, FLOAT8OID,
757 /* hard-wired info on type float8 */
758 8, FLOAT8PASSBYVAL, 'd',
763 if (num_percentiles == 0)
764 PG_RETURN_POINTER(construct_empty_array(osastate->qstate->sortColType));
766 pct_info = setup_pct_info(num_percentiles,
769 osastate->number_of_rows,
772 result_datum = (Datum *) palloc(num_percentiles * sizeof(Datum));
773 result_isnull = (bool *) palloc(num_percentiles * sizeof(bool));
776 * Start by dealing with any nulls in the param array - those are sorted
777 * to the front on row=0, so set the corresponding result indexes to null
779 for (i = 0; i < num_percentiles; i++)
781 int idx = pct_info[i].idx;
783 if (pct_info[i].first_row > 0)
786 result_datum[idx] = (Datum) 0;
787 result_isnull[idx] = true;
791 * If there's anything left after doing the nulls, then grind the input
792 * and extract the needed values
794 if (i < num_percentiles)
796 /* Finish the sort, or rescan if we already did */
797 if (!osastate->sort_done)
799 tuplesort_performsort(osastate->sortstate);
800 osastate->sort_done = true;
803 tuplesort_rescan(osastate->sortstate);
805 for (; i < num_percentiles; i++)
807 int64 target_row = pct_info[i].first_row;
808 int idx = pct_info[i].idx;
810 /* Advance to target row, if not already there */
811 if (target_row > rownum)
813 if (!tuplesort_skiptuples(osastate->sortstate, target_row - rownum - 1, true))
814 elog(ERROR, "missing row in percentile_disc");
816 if (!tuplesort_getdatum(osastate->sortstate, true, &val, &isnull, NULL))
817 elog(ERROR, "missing row in percentile_disc");
822 result_datum[idx] = val;
823 result_isnull[idx] = isnull;
827 /* We make the output array the same shape as the input */
828 PG_RETURN_POINTER(construct_md_array(result_datum, result_isnull,
832 osastate->qstate->sortColType,
833 osastate->qstate->typLen,
834 osastate->qstate->typByVal,
835 osastate->qstate->typAlign));
839 * percentile_cont(float8[]) within group () - continuous percentiles
842 percentile_cont_multi_final_common(FunctionCallInfo fcinfo,
844 int16 typLen, bool typByVal, char typAlign,
847 OSAPerGroupState *osastate;
849 Datum *percentiles_datum;
850 bool *percentiles_null;
852 struct pct_info *pct_info;
856 Datum first_val = (Datum) 0;
857 Datum second_val = (Datum) 0;
861 Assert(AggCheckCallContext(fcinfo, NULL) == AGG_CONTEXT_AGGREGATE);
863 /* If there were no regular rows, the result is NULL */
867 osastate = (OSAPerGroupState *) PG_GETARG_POINTER(0);
869 /* number_of_rows could be zero if we only saw NULL input values */
870 if (osastate->number_of_rows == 0)
873 Assert(expect_type == osastate->qstate->sortColType);
875 /* Deconstruct the percentile-array input */
878 param = PG_GETARG_ARRAYTYPE_P(1);
880 deconstruct_array(param, FLOAT8OID,
881 /* hard-wired info on type float8 */
882 8, FLOAT8PASSBYVAL, 'd',
887 if (num_percentiles == 0)
888 PG_RETURN_POINTER(construct_empty_array(osastate->qstate->sortColType));
890 pct_info = setup_pct_info(num_percentiles,
893 osastate->number_of_rows,
896 result_datum = (Datum *) palloc(num_percentiles * sizeof(Datum));
897 result_isnull = (bool *) palloc(num_percentiles * sizeof(bool));
900 * Start by dealing with any nulls in the param array - those are sorted
901 * to the front on row=0, so set the corresponding result indexes to null
903 for (i = 0; i < num_percentiles; i++)
905 int idx = pct_info[i].idx;
907 if (pct_info[i].first_row > 0)
910 result_datum[idx] = (Datum) 0;
911 result_isnull[idx] = true;
915 * If there's anything left after doing the nulls, then grind the input
916 * and extract the needed values
918 if (i < num_percentiles)
920 /* Finish the sort, or rescan if we already did */
921 if (!osastate->sort_done)
923 tuplesort_performsort(osastate->sortstate);
924 osastate->sort_done = true;
927 tuplesort_rescan(osastate->sortstate);
929 for (; i < num_percentiles; i++)
931 int64 first_row = pct_info[i].first_row;
932 int64 second_row = pct_info[i].second_row;
933 int idx = pct_info[i].idx;
936 * Advance to first_row, if not already there. Note that we might
937 * already have rownum beyond first_row, in which case first_val
938 * is already correct. (This occurs when interpolating between
939 * the same two input rows as for the previous percentile.)
941 if (first_row > rownum)
943 if (!tuplesort_skiptuples(osastate->sortstate, first_row - rownum - 1, true))
944 elog(ERROR, "missing row in percentile_cont");
946 if (!tuplesort_getdatum(osastate->sortstate, true, &first_val,
947 &isnull, NULL) || isnull)
948 elog(ERROR, "missing row in percentile_cont");
951 /* Always advance second_val to be latest input value */
952 second_val = first_val;
954 else if (first_row == rownum)
957 * We are already at the desired row, so we must previously
958 * have read its value into second_val (and perhaps first_val
959 * as well, but this assignment is harmless in that case).
961 first_val = second_val;
964 /* Fetch second_row if needed */
965 if (second_row > rownum)
967 if (!tuplesort_getdatum(osastate->sortstate, true, &second_val,
968 &isnull, NULL) || isnull)
969 elog(ERROR, "missing row in percentile_cont");
972 /* We should now certainly be on second_row exactly */
973 Assert(second_row == rownum);
975 /* Compute appropriate result */
976 if (second_row > first_row)
977 result_datum[idx] = lerpfunc(first_val, second_val,
978 pct_info[i].proportion);
980 result_datum[idx] = first_val;
982 result_isnull[idx] = false;
986 /* We make the output array the same shape as the input */
987 PG_RETURN_POINTER(construct_md_array(result_datum, result_isnull,
989 ARR_DIMS(param), ARR_LBOUND(param),
997 * percentile_cont(float8[]) within group (float8) - continuous percentiles
1000 percentile_cont_float8_multi_final(PG_FUNCTION_ARGS)
1002 return percentile_cont_multi_final_common(fcinfo,
1004 /* hard-wired info on type float8 */
1005 8, FLOAT8PASSBYVAL, 'd',
1010 * percentile_cont(float8[]) within group (interval) - continuous percentiles
1013 percentile_cont_interval_multi_final(PG_FUNCTION_ARGS)
1015 return percentile_cont_multi_final_common(fcinfo,
1017 /* hard-wired info on type interval */
1024 * mode() within group (anyelement) - most common value
1027 mode_final(PG_FUNCTION_ARGS)
1029 OSAPerGroupState *osastate;
1032 Datum mode_val = (Datum) 0;
1033 int64 mode_freq = 0;
1034 Datum last_val = (Datum) 0;
1035 int64 last_val_freq = 0;
1036 bool last_val_is_mode = false;
1038 Datum abbrev_val = (Datum) 0;
1039 Datum last_abbrev_val = (Datum) 0;
1042 Assert(AggCheckCallContext(fcinfo, NULL) == AGG_CONTEXT_AGGREGATE);
1044 /* If there were no regular rows, the result is NULL */
1045 if (PG_ARGISNULL(0))
1048 osastate = (OSAPerGroupState *) PG_GETARG_POINTER(0);
1050 /* number_of_rows could be zero if we only saw NULL input values */
1051 if (osastate->number_of_rows == 0)
1054 /* Look up the equality function for the datatype, if we didn't already */
1055 equalfn = &(osastate->qstate->equalfn);
1056 if (!OidIsValid(equalfn->fn_oid))
1057 fmgr_info_cxt(get_opcode(osastate->qstate->eqOperator), equalfn,
1058 osastate->qstate->qcontext);
1060 shouldfree = !(osastate->qstate->typByVal);
1062 /* Finish the sort, or rescan if we already did */
1063 if (!osastate->sort_done)
1065 tuplesort_performsort(osastate->sortstate);
1066 osastate->sort_done = true;
1069 tuplesort_rescan(osastate->sortstate);
1071 /* Scan tuples and count frequencies */
1072 while (tuplesort_getdatum(osastate->sortstate, true, &val, &isnull, &abbrev_val))
1074 /* we don't expect any nulls, but ignore them if found */
1078 if (last_val_freq == 0)
1080 /* first nonnull value - it's the mode for now */
1081 mode_val = last_val = val;
1082 mode_freq = last_val_freq = 1;
1083 last_val_is_mode = true;
1084 last_abbrev_val = abbrev_val;
1086 else if (abbrev_val == last_abbrev_val &&
1087 DatumGetBool(FunctionCall2Coll(equalfn, PG_GET_COLLATION(), val, last_val)))
1089 /* value equal to previous value, count it */
1090 if (last_val_is_mode)
1091 mode_freq++; /* needn't maintain last_val_freq */
1092 else if (++last_val_freq > mode_freq)
1094 /* last_val becomes new mode */
1096 pfree(DatumGetPointer(mode_val));
1097 mode_val = last_val;
1098 mode_freq = last_val_freq;
1099 last_val_is_mode = true;
1102 pfree(DatumGetPointer(val));
1106 /* val should replace last_val */
1107 if (shouldfree && !last_val_is_mode)
1108 pfree(DatumGetPointer(last_val));
1110 /* avoid equality function calls by reusing abbreviated keys */
1111 last_abbrev_val = abbrev_val;
1113 last_val_is_mode = false;
1116 CHECK_FOR_INTERRUPTS();
1119 if (shouldfree && !last_val_is_mode)
1120 pfree(DatumGetPointer(last_val));
1123 PG_RETURN_DATUM(mode_val);
1130 * Common code to sanity-check args for hypothetical-set functions. No need
1131 * for friendly errors, these can only happen if someone's messing up the
1132 * aggregate definitions. The checks are needed for security, however.
1135 hypothetical_check_argtypes(FunctionCallInfo fcinfo, int nargs,
1140 /* check that we have an int4 flag column */
1142 (nargs + 1) != tupdesc->natts ||
1143 TupleDescAttr(tupdesc, nargs)->atttypid != INT4OID)
1144 elog(ERROR, "type mismatch in hypothetical-set function");
1146 /* check that direct args match in type with aggregated args */
1147 for (i = 0; i < nargs; i++)
1149 Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1151 if (get_fn_expr_argtype(fcinfo->flinfo, i + 1) != attr->atttypid)
1152 elog(ERROR, "type mismatch in hypothetical-set function");
1157 * compute rank of hypothetical row
1159 * flag should be -1 to sort hypothetical row ahead of its peers, or +1
1161 * total number of regular rows is returned into *number_of_rows.
1164 hypothetical_rank_common(FunctionCallInfo fcinfo, int flag,
1165 int64 *number_of_rows)
1167 int nargs = PG_NARGS() - 1;
1169 OSAPerGroupState *osastate;
1170 TupleTableSlot *slot;
1173 Assert(AggCheckCallContext(fcinfo, NULL) == AGG_CONTEXT_AGGREGATE);
1175 /* If there were no regular rows, the rank is always 1 */
1176 if (PG_ARGISNULL(0))
1178 *number_of_rows = 0;
1182 osastate = (OSAPerGroupState *) PG_GETARG_POINTER(0);
1183 *number_of_rows = osastate->number_of_rows;
1185 /* Adjust nargs to be the number of direct (or aggregated) args */
1187 elog(ERROR, "wrong number of arguments in hypothetical-set function");
1190 hypothetical_check_argtypes(fcinfo, nargs, osastate->qstate->tupdesc);
1192 /* because we need a hypothetical row, we can't share transition state */
1193 Assert(!osastate->sort_done);
1195 /* insert the hypothetical row into the sort */
1196 slot = osastate->qstate->tupslot;
1197 ExecClearTuple(slot);
1198 for (i = 0; i < nargs; i++)
1200 slot->tts_values[i] = PG_GETARG_DATUM(i + 1);
1201 slot->tts_isnull[i] = PG_ARGISNULL(i + 1);
1203 slot->tts_values[i] = Int32GetDatum(flag);
1204 slot->tts_isnull[i] = false;
1205 ExecStoreVirtualTuple(slot);
1207 tuplesort_puttupleslot(osastate->sortstate, slot);
1209 /* finish the sort */
1210 tuplesort_performsort(osastate->sortstate);
1211 osastate->sort_done = true;
1213 /* iterate till we find the hypothetical row */
1214 while (tuplesort_gettupleslot(osastate->sortstate, true, true, slot, NULL))
1217 Datum d = slot_getattr(slot, nargs + 1, &isnull);
1219 if (!isnull && DatumGetInt32(d) != 0)
1224 CHECK_FOR_INTERRUPTS();
1227 ExecClearTuple(slot);
1234 * rank() - rank of hypothetical row
1237 hypothetical_rank_final(PG_FUNCTION_ARGS)
1242 rank = hypothetical_rank_common(fcinfo, -1, &rowcount);
1244 PG_RETURN_INT64(rank);
1248 * percent_rank() - percentile rank of hypothetical row
1251 hypothetical_percent_rank_final(PG_FUNCTION_ARGS)
1257 rank = hypothetical_rank_common(fcinfo, -1, &rowcount);
1260 PG_RETURN_FLOAT8(0);
1262 result_val = (double) (rank - 1) / (double) (rowcount);
1264 PG_RETURN_FLOAT8(result_val);
1268 * cume_dist() - cumulative distribution of hypothetical row
1271 hypothetical_cume_dist_final(PG_FUNCTION_ARGS)
1277 rank = hypothetical_rank_common(fcinfo, 1, &rowcount);
1279 result_val = (double) (rank) / (double) (rowcount + 1);
1281 PG_RETURN_FLOAT8(result_val);
1285 * dense_rank() - rank of hypothetical row without gaps in ranking
1288 hypothetical_dense_rank_final(PG_FUNCTION_ARGS)
1290 ExprContext *econtext;
1291 ExprState *compareTuple;
1292 int nargs = PG_NARGS() - 1;
1294 int64 duplicate_count = 0;
1295 OSAPerGroupState *osastate;
1296 int numDistinctCols;
1297 Datum abbrevVal = (Datum) 0;
1298 Datum abbrevOld = (Datum) 0;
1299 TupleTableSlot *slot;
1300 TupleTableSlot *extraslot;
1301 TupleTableSlot *slot2;
1304 Assert(AggCheckCallContext(fcinfo, NULL) == AGG_CONTEXT_AGGREGATE);
1306 /* If there were no regular rows, the rank is always 1 */
1307 if (PG_ARGISNULL(0))
1308 PG_RETURN_INT64(rank);
1310 osastate = (OSAPerGroupState *) PG_GETARG_POINTER(0);
1311 econtext = osastate->qstate->econtext;
1314 MemoryContext oldcontext;
1316 /* Make sure to we create econtext under correct parent context. */
1317 oldcontext = MemoryContextSwitchTo(osastate->qstate->qcontext);
1318 osastate->qstate->econtext = CreateStandaloneExprContext();
1319 econtext = osastate->qstate->econtext;
1320 MemoryContextSwitchTo(oldcontext);
1323 /* Adjust nargs to be the number of direct (or aggregated) args */
1325 elog(ERROR, "wrong number of arguments in hypothetical-set function");
1328 hypothetical_check_argtypes(fcinfo, nargs, osastate->qstate->tupdesc);
1331 * When comparing tuples, we can omit the flag column since we will only
1332 * compare rows with flag == 0.
1334 numDistinctCols = osastate->qstate->numSortCols - 1;
1336 /* Build tuple comparator, if we didn't already */
1337 compareTuple = osastate->qstate->compareTuple;
1338 if (compareTuple == NULL)
1340 AttrNumber *sortColIdx = osastate->qstate->sortColIdx;
1341 MemoryContext oldContext;
1343 oldContext = MemoryContextSwitchTo(osastate->qstate->qcontext);
1344 compareTuple = execTuplesMatchPrepare(osastate->qstate->tupdesc,
1347 osastate->qstate->eqOperators,
1348 osastate->qstate->sortCollations,
1350 MemoryContextSwitchTo(oldContext);
1351 osastate->qstate->compareTuple = compareTuple;
1354 /* because we need a hypothetical row, we can't share transition state */
1355 Assert(!osastate->sort_done);
1357 /* insert the hypothetical row into the sort */
1358 slot = osastate->qstate->tupslot;
1359 ExecClearTuple(slot);
1360 for (i = 0; i < nargs; i++)
1362 slot->tts_values[i] = PG_GETARG_DATUM(i + 1);
1363 slot->tts_isnull[i] = PG_ARGISNULL(i + 1);
1365 slot->tts_values[i] = Int32GetDatum(-1);
1366 slot->tts_isnull[i] = false;
1367 ExecStoreVirtualTuple(slot);
1369 tuplesort_puttupleslot(osastate->sortstate, slot);
1371 /* finish the sort */
1372 tuplesort_performsort(osastate->sortstate);
1373 osastate->sort_done = true;
1376 * We alternate fetching into tupslot and extraslot so that we have the
1377 * previous row available for comparisons. This is accomplished by
1378 * swapping the slot pointer variables after each row.
1380 extraslot = MakeSingleTupleTableSlot(osastate->qstate->tupdesc,
1381 &TTSOpsMinimalTuple);
1384 /* iterate till we find the hypothetical row */
1385 while (tuplesort_gettupleslot(osastate->sortstate, true, true, slot,
1389 Datum d = slot_getattr(slot, nargs + 1, &isnull);
1390 TupleTableSlot *tmpslot;
1392 if (!isnull && DatumGetInt32(d) != 0)
1395 /* count non-distinct tuples */
1396 econtext->ecxt_outertuple = slot;
1397 econtext->ecxt_innertuple = slot2;
1399 if (!TupIsNull(slot2) &&
1400 abbrevVal == abbrevOld &&
1401 ExecQualAndReset(compareTuple, econtext))
1407 /* avoid ExecQual() calls by reusing abbreviated keys */
1408 abbrevOld = abbrevVal;
1412 CHECK_FOR_INTERRUPTS();
1415 ExecClearTuple(slot);
1416 ExecClearTuple(slot2);
1418 ExecDropSingleTupleTableSlot(extraslot);
1420 rank = rank - duplicate_count;
1422 PG_RETURN_INT64(rank);