PostgreSQL Source Code  git master
nodeWindowAgg.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * nodeWindowAgg.c
4  * routines to handle WindowAgg nodes.
5  *
6  * A WindowAgg node evaluates "window functions" across suitable partitions
7  * of the input tuple set. Any one WindowAgg works for just a single window
8  * specification, though it can evaluate multiple window functions sharing
9  * identical window specifications. The input tuples are required to be
10  * delivered in sorted order, with the PARTITION BY columns (if any) as
11  * major sort keys and the ORDER BY columns (if any) as minor sort keys.
12  * (The planner generates a stack of WindowAggs with intervening Sort nodes
13  * as needed, if a query involves more than one window specification.)
14  *
15  * Since window functions can require access to any or all of the rows in
16  * the current partition, we accumulate rows of the partition into a
17  * tuplestore. The window functions are called using the WindowObject API
18  * so that they can access those rows as needed.
19  *
20  * We also support using plain aggregate functions as window functions.
21  * For these, the regular Agg-node environment is emulated for each partition.
22  * As required by the SQL spec, the output represents the value of the
23  * aggregate function over all rows in the current row's window frame.
24  *
25  *
26  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
27  * Portions Copyright (c) 1994, Regents of the University of California
28  *
29  * IDENTIFICATION
30  * src/backend/executor/nodeWindowAgg.c
31  *
32  *-------------------------------------------------------------------------
33  */
34 #include "postgres.h"
35 
36 #include "access/htup_details.h"
37 #include "catalog/objectaccess.h"
38 #include "catalog/pg_aggregate.h"
39 #include "catalog/pg_proc.h"
40 #include "executor/executor.h"
41 #include "executor/nodeWindowAgg.h"
42 #include "miscadmin.h"
43 #include "nodes/nodeFuncs.h"
44 #include "optimizer/optimizer.h"
45 #include "parser/parse_agg.h"
46 #include "parser/parse_coerce.h"
47 #include "utils/acl.h"
48 #include "utils/builtins.h"
49 #include "utils/datum.h"
50 #include "utils/expandeddatum.h"
51 #include "utils/lsyscache.h"
52 #include "utils/memutils.h"
53 #include "utils/regproc.h"
54 #include "utils/syscache.h"
55 #include "windowapi.h"
56 
57 /*
58  * All the window function APIs are called with this object, which is passed
59  * to window functions as fcinfo->context.
60  */
61 typedef struct WindowObjectData
62 {
64  WindowAggState *winstate; /* parent WindowAggState */
65  List *argstates; /* ExprState trees for fn's arguments */
66  void *localmem; /* WinGetPartitionLocalMemory's chunk */
67  int markptr; /* tuplestore mark pointer for this fn */
68  int readptr; /* tuplestore read pointer for this fn */
69  int64 markpos; /* row that markptr is positioned on */
70  int64 seekpos; /* row that readptr is positioned on */
72 
73 /*
74  * We have one WindowStatePerFunc struct for each window function and
75  * window aggregate handled by this node.
76  */
77 typedef struct WindowStatePerFuncData
78 {
79  /* Links to WindowFunc expr and state nodes this working state is for */
82 
83  int numArguments; /* number of arguments */
84 
85  FmgrInfo flinfo; /* fmgr lookup data for window function */
86 
87  Oid winCollation; /* collation derived for window function */
88 
89  /*
90  * We need the len and byval info for the result of each function in order
91  * to know how to copy/delete values.
92  */
95 
96  bool plain_agg; /* is it just a plain aggregate function? */
97  int aggno; /* if so, index of its WindowStatePerAggData */
98 
99  WindowObject winobj; /* object used in window function API */
101 
102 /*
103  * For plain aggregate window functions, we also have one of these.
104  */
105 typedef struct WindowStatePerAggData
106 {
107  /* Oids of transition functions */
109  Oid invtransfn_oid; /* may be InvalidOid */
110  Oid finalfn_oid; /* may be InvalidOid */
111 
112  /*
113  * fmgr lookup data for transition functions --- only valid when
114  * corresponding oid is not InvalidOid. Note in particular that fn_strict
115  * flags are kept here.
116  */
120 
121  int numFinalArgs; /* number of arguments to pass to finalfn */
122 
123  /*
124  * initial value from pg_aggregate entry
125  */
128 
129  /*
130  * cached value for current frame boundaries
131  */
134 
135  /*
136  * We need the len and byval info for the agg's input, result, and
137  * transition data types in order to know how to copy/delete values.
138  */
145 
146  int wfuncno; /* index of associated WindowStatePerFuncData */
147 
148  /* Context holding transition value and possibly other subsidiary data */
149  MemoryContext aggcontext; /* may be private, or winstate->aggcontext */
150 
151  /* Current transition value */
152  Datum transValue; /* current transition value */
154 
155  int64 transValueCount; /* number of currently-aggregated rows */
156 
157  /* Data local to eval_windowaggregates() */
158  bool restart; /* need to restart this agg in this cycle? */
160 
161 static void initialize_windowaggregate(WindowAggState *winstate,
162  WindowStatePerFunc perfuncstate,
163  WindowStatePerAgg peraggstate);
164 static void advance_windowaggregate(WindowAggState *winstate,
165  WindowStatePerFunc perfuncstate,
166  WindowStatePerAgg peraggstate);
167 static bool advance_windowaggregate_base(WindowAggState *winstate,
168  WindowStatePerFunc perfuncstate,
169  WindowStatePerAgg peraggstate);
170 static void finalize_windowaggregate(WindowAggState *winstate,
171  WindowStatePerFunc perfuncstate,
172  WindowStatePerAgg peraggstate,
173  Datum *result, bool *isnull);
174 
175 static void eval_windowaggregates(WindowAggState *winstate);
176 static void eval_windowfunction(WindowAggState *winstate,
177  WindowStatePerFunc perfuncstate,
178  Datum *result, bool *isnull);
179 
180 static void begin_partition(WindowAggState *winstate);
181 static void spool_tuples(WindowAggState *winstate, int64 pos);
182 static void release_partition(WindowAggState *winstate);
183 
184 static int row_is_in_frame(WindowAggState *winstate, int64 pos,
185  TupleTableSlot *slot);
186 static void update_frameheadpos(WindowAggState *winstate);
187 static void update_frametailpos(WindowAggState *winstate);
188 static void update_grouptailpos(WindowAggState *winstate);
189 
191  WindowFunc *wfunc,
192  WindowStatePerAgg peraggstate);
193 static Datum GetAggInitVal(Datum textInitVal, Oid transtype);
194 
195 static bool are_peers(WindowAggState *winstate, TupleTableSlot *slot1,
196  TupleTableSlot *slot2);
197 static bool window_gettupleslot(WindowObject winobj, int64 pos,
198  TupleTableSlot *slot);
199 
200 
201 /*
202  * initialize_windowaggregate
203  * parallel to initialize_aggregates in nodeAgg.c
204  */
205 static void
207  WindowStatePerFunc perfuncstate,
208  WindowStatePerAgg peraggstate)
209 {
210  MemoryContext oldContext;
211 
212  /*
213  * If we're using a private aggcontext, we may reset it here. But if the
214  * context is shared, we don't know which other aggregates may still need
215  * it, so we must leave it to the caller to reset at an appropriate time.
216  */
217  if (peraggstate->aggcontext != winstate->aggcontext)
219 
220  if (peraggstate->initValueIsNull)
221  peraggstate->transValue = peraggstate->initValue;
222  else
223  {
224  oldContext = MemoryContextSwitchTo(peraggstate->aggcontext);
225  peraggstate->transValue = datumCopy(peraggstate->initValue,
226  peraggstate->transtypeByVal,
227  peraggstate->transtypeLen);
228  MemoryContextSwitchTo(oldContext);
229  }
230  peraggstate->transValueIsNull = peraggstate->initValueIsNull;
231  peraggstate->transValueCount = 0;
232  peraggstate->resultValue = (Datum) 0;
233  peraggstate->resultValueIsNull = true;
234 }
235 
236 /*
237  * advance_windowaggregate
238  * parallel to advance_aggregates in nodeAgg.c
239  */
240 static void
242  WindowStatePerFunc perfuncstate,
243  WindowStatePerAgg peraggstate)
244 {
245  LOCAL_FCINFO(fcinfo, FUNC_MAX_ARGS);
246  WindowFuncExprState *wfuncstate = perfuncstate->wfuncstate;
247  int numArguments = perfuncstate->numArguments;
248  Datum newVal;
249  ListCell *arg;
250  int i;
251  MemoryContext oldContext;
252  ExprContext *econtext = winstate->tmpcontext;
253  ExprState *filter = wfuncstate->aggfilter;
254 
255  oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
256 
257  /* Skip anything FILTERed out */
258  if (filter)
259  {
260  bool isnull;
261  Datum res = ExecEvalExpr(filter, econtext, &isnull);
262 
263  if (isnull || !DatumGetBool(res))
264  {
265  MemoryContextSwitchTo(oldContext);
266  return;
267  }
268  }
269 
270  /* We start from 1, since the 0th arg will be the transition value */
271  i = 1;
272  foreach(arg, wfuncstate->args)
273  {
274  ExprState *argstate = (ExprState *) lfirst(arg);
275 
276  fcinfo->args[i].value = ExecEvalExpr(argstate, econtext,
277  &fcinfo->args[i].isnull);
278  i++;
279  }
280 
281  if (peraggstate->transfn.fn_strict)
282  {
283  /*
284  * For a strict transfn, nothing happens when there's a NULL input; we
285  * just keep the prior transValue. Note transValueCount doesn't
286  * change either.
287  */
288  for (i = 1; i <= numArguments; i++)
289  {
290  if (fcinfo->args[i].isnull)
291  {
292  MemoryContextSwitchTo(oldContext);
293  return;
294  }
295  }
296 
297  /*
298  * For strict transition functions with initial value NULL we use the
299  * first non-NULL input as the initial state. (We already checked
300  * that the agg's input type is binary-compatible with its transtype,
301  * so straight copy here is OK.)
302  *
303  * We must copy the datum into aggcontext if it is pass-by-ref. We do
304  * not need to pfree the old transValue, since it's NULL.
305  */
306  if (peraggstate->transValueCount == 0 && peraggstate->transValueIsNull)
307  {
308  MemoryContextSwitchTo(peraggstate->aggcontext);
309  peraggstate->transValue = datumCopy(fcinfo->args[1].value,
310  peraggstate->transtypeByVal,
311  peraggstate->transtypeLen);
312  peraggstate->transValueIsNull = false;
313  peraggstate->transValueCount = 1;
314  MemoryContextSwitchTo(oldContext);
315  return;
316  }
317 
318  if (peraggstate->transValueIsNull)
319  {
320  /*
321  * Don't call a strict function with NULL inputs. Note it is
322  * possible to get here despite the above tests, if the transfn is
323  * strict *and* returned a NULL on a prior cycle. If that happens
324  * we will propagate the NULL all the way to the end. That can
325  * only happen if there's no inverse transition function, though,
326  * since we disallow transitions back to NULL when there is one.
327  */
328  MemoryContextSwitchTo(oldContext);
329  Assert(!OidIsValid(peraggstate->invtransfn_oid));
330  return;
331  }
332  }
333 
334  /*
335  * OK to call the transition function. Set winstate->curaggcontext while
336  * calling it, for possible use by AggCheckCallContext.
337  */
338  InitFunctionCallInfoData(*fcinfo, &(peraggstate->transfn),
339  numArguments + 1,
340  perfuncstate->winCollation,
341  (void *) winstate, NULL);
342  fcinfo->args[0].value = peraggstate->transValue;
343  fcinfo->args[0].isnull = peraggstate->transValueIsNull;
344  winstate->curaggcontext = peraggstate->aggcontext;
345  newVal = FunctionCallInvoke(fcinfo);
346  winstate->curaggcontext = NULL;
347 
348  /*
349  * Moving-aggregate transition functions must not return null, see
350  * advance_windowaggregate_base().
351  */
352  if (fcinfo->isnull && OidIsValid(peraggstate->invtransfn_oid))
353  ereport(ERROR,
354  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
355  errmsg("moving-aggregate transition function must not return null")));
356 
357  /*
358  * We must track the number of rows included in transValue, since to
359  * remove the last input, advance_windowaggregate_base() mustn't call the
360  * inverse transition function, but simply reset transValue back to its
361  * initial value.
362  */
363  peraggstate->transValueCount++;
364 
365  /*
366  * If pass-by-ref datatype, must copy the new value into aggcontext and
367  * free the prior transValue. But if transfn returned a pointer to its
368  * first input, we don't need to do anything. Also, if transfn returned a
369  * pointer to a R/W expanded object that is already a child of the
370  * aggcontext, assume we can adopt that value without copying it.
371  */
372  if (!peraggstate->transtypeByVal &&
373  DatumGetPointer(newVal) != DatumGetPointer(peraggstate->transValue))
374  {
375  if (!fcinfo->isnull)
376  {
377  MemoryContextSwitchTo(peraggstate->aggcontext);
379  false,
380  peraggstate->transtypeLen) &&
382  /* do nothing */ ;
383  else
384  newVal = datumCopy(newVal,
385  peraggstate->transtypeByVal,
386  peraggstate->transtypeLen);
387  }
388  if (!peraggstate->transValueIsNull)
389  {
391  false,
392  peraggstate->transtypeLen))
393  DeleteExpandedObject(peraggstate->transValue);
394  else
395  pfree(DatumGetPointer(peraggstate->transValue));
396  }
397  }
398 
399  MemoryContextSwitchTo(oldContext);
400  peraggstate->transValue = newVal;
401  peraggstate->transValueIsNull = fcinfo->isnull;
402 }
403 
404 /*
405  * advance_windowaggregate_base
406  * Remove the oldest tuple from an aggregation.
407  *
408  * This is very much like advance_windowaggregate, except that we will call
409  * the inverse transition function (which caller must have checked is
410  * available).
411  *
412  * Returns true if we successfully removed the current row from this
413  * aggregate, false if not (in the latter case, caller is responsible
414  * for cleaning up by restarting the aggregation).
415  */
416 static bool
418  WindowStatePerFunc perfuncstate,
419  WindowStatePerAgg peraggstate)
420 {
421  LOCAL_FCINFO(fcinfo, FUNC_MAX_ARGS);
422  WindowFuncExprState *wfuncstate = perfuncstate->wfuncstate;
423  int numArguments = perfuncstate->numArguments;
424  Datum newVal;
425  ListCell *arg;
426  int i;
427  MemoryContext oldContext;
428  ExprContext *econtext = winstate->tmpcontext;
429  ExprState *filter = wfuncstate->aggfilter;
430 
431  oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
432 
433  /* Skip anything FILTERed out */
434  if (filter)
435  {
436  bool isnull;
437  Datum res = ExecEvalExpr(filter, econtext, &isnull);
438 
439  if (isnull || !DatumGetBool(res))
440  {
441  MemoryContextSwitchTo(oldContext);
442  return true;
443  }
444  }
445 
446  /* We start from 1, since the 0th arg will be the transition value */
447  i = 1;
448  foreach(arg, wfuncstate->args)
449  {
450  ExprState *argstate = (ExprState *) lfirst(arg);
451 
452  fcinfo->args[i].value = ExecEvalExpr(argstate, econtext,
453  &fcinfo->args[i].isnull);
454  i++;
455  }
456 
457  if (peraggstate->invtransfn.fn_strict)
458  {
459  /*
460  * For a strict (inv)transfn, nothing happens when there's a NULL
461  * input; we just keep the prior transValue. Note transValueCount
462  * doesn't change either.
463  */
464  for (i = 1; i <= numArguments; i++)
465  {
466  if (fcinfo->args[i].isnull)
467  {
468  MemoryContextSwitchTo(oldContext);
469  return true;
470  }
471  }
472  }
473 
474  /* There should still be an added but not yet removed value */
475  Assert(peraggstate->transValueCount > 0);
476 
477  /*
478  * In moving-aggregate mode, the state must never be NULL, except possibly
479  * before any rows have been aggregated (which is surely not the case at
480  * this point). This restriction allows us to interpret a NULL result
481  * from the inverse function as meaning "sorry, can't do an inverse
482  * transition in this case". We already checked this in
483  * advance_windowaggregate, but just for safety, check again.
484  */
485  if (peraggstate->transValueIsNull)
486  elog(ERROR, "aggregate transition value is NULL before inverse transition");
487 
488  /*
489  * We mustn't use the inverse transition function to remove the last
490  * input. Doing so would yield a non-NULL state, whereas we should be in
491  * the initial state afterwards which may very well be NULL. So instead,
492  * we simply re-initialize the aggregate in this case.
493  */
494  if (peraggstate->transValueCount == 1)
495  {
496  MemoryContextSwitchTo(oldContext);
498  &winstate->perfunc[peraggstate->wfuncno],
499  peraggstate);
500  return true;
501  }
502 
503  /*
504  * OK to call the inverse transition function. Set
505  * winstate->curaggcontext while calling it, for possible use by
506  * AggCheckCallContext.
507  */
508  InitFunctionCallInfoData(*fcinfo, &(peraggstate->invtransfn),
509  numArguments + 1,
510  perfuncstate->winCollation,
511  (void *) winstate, NULL);
512  fcinfo->args[0].value = peraggstate->transValue;
513  fcinfo->args[0].isnull = peraggstate->transValueIsNull;
514  winstate->curaggcontext = peraggstate->aggcontext;
515  newVal = FunctionCallInvoke(fcinfo);
516  winstate->curaggcontext = NULL;
517 
518  /*
519  * If the function returns NULL, report failure, forcing a restart.
520  */
521  if (fcinfo->isnull)
522  {
523  MemoryContextSwitchTo(oldContext);
524  return false;
525  }
526 
527  /* Update number of rows included in transValue */
528  peraggstate->transValueCount--;
529 
530  /*
531  * If pass-by-ref datatype, must copy the new value into aggcontext and
532  * free the prior transValue. But if invtransfn returned a pointer to its
533  * first input, we don't need to do anything. Also, if invtransfn
534  * returned a pointer to a R/W expanded object that is already a child of
535  * the aggcontext, assume we can adopt that value without copying it.
536  *
537  * Note: the checks for null values here will never fire, but it seems
538  * best to have this stanza look just like advance_windowaggregate.
539  */
540  if (!peraggstate->transtypeByVal &&
541  DatumGetPointer(newVal) != DatumGetPointer(peraggstate->transValue))
542  {
543  if (!fcinfo->isnull)
544  {
545  MemoryContextSwitchTo(peraggstate->aggcontext);
547  false,
548  peraggstate->transtypeLen) &&
550  /* do nothing */ ;
551  else
552  newVal = datumCopy(newVal,
553  peraggstate->transtypeByVal,
554  peraggstate->transtypeLen);
555  }
556  if (!peraggstate->transValueIsNull)
557  {
559  false,
560  peraggstate->transtypeLen))
561  DeleteExpandedObject(peraggstate->transValue);
562  else
563  pfree(DatumGetPointer(peraggstate->transValue));
564  }
565  }
566 
567  MemoryContextSwitchTo(oldContext);
568  peraggstate->transValue = newVal;
569  peraggstate->transValueIsNull = fcinfo->isnull;
570 
571  return true;
572 }
573 
574 /*
575  * finalize_windowaggregate
576  * parallel to finalize_aggregate in nodeAgg.c
577  */
578 static void
580  WindowStatePerFunc perfuncstate,
581  WindowStatePerAgg peraggstate,
582  Datum *result, bool *isnull)
583 {
584  MemoryContext oldContext;
585 
587 
588  /*
589  * Apply the agg's finalfn if one is provided, else return transValue.
590  */
591  if (OidIsValid(peraggstate->finalfn_oid))
592  {
593  LOCAL_FCINFO(fcinfo, FUNC_MAX_ARGS);
594  int numFinalArgs = peraggstate->numFinalArgs;
595  bool anynull;
596  int i;
597 
598  InitFunctionCallInfoData(fcinfodata.fcinfo, &(peraggstate->finalfn),
599  numFinalArgs,
600  perfuncstate->winCollation,
601  (void *) winstate, NULL);
602  fcinfo->args[0].value =
604  peraggstate->transValueIsNull,
605  peraggstate->transtypeLen);
606  fcinfo->args[0].isnull = peraggstate->transValueIsNull;
607  anynull = peraggstate->transValueIsNull;
608 
609  /* Fill any remaining argument positions with nulls */
610  for (i = 1; i < numFinalArgs; i++)
611  {
612  fcinfo->args[i].value = (Datum) 0;
613  fcinfo->args[i].isnull = true;
614  anynull = true;
615  }
616 
617  if (fcinfo->flinfo->fn_strict && anynull)
618  {
619  /* don't call a strict function with NULL inputs */
620  *result = (Datum) 0;
621  *isnull = true;
622  }
623  else
624  {
625  winstate->curaggcontext = peraggstate->aggcontext;
626  *result = FunctionCallInvoke(fcinfo);
627  winstate->curaggcontext = NULL;
628  *isnull = fcinfo->isnull;
629  }
630  }
631  else
632  {
633  *result =
635  peraggstate->transValueIsNull,
636  peraggstate->transtypeLen);
637  *isnull = peraggstate->transValueIsNull;
638  }
639 
640  MemoryContextSwitchTo(oldContext);
641 }
642 
643 /*
644  * eval_windowaggregates
645  * evaluate plain aggregates being used as window functions
646  *
647  * This differs from nodeAgg.c in two ways. First, if the window's frame
648  * start position moves, we use the inverse transition function (if it exists)
649  * to remove rows from the transition value. And second, we expect to be
650  * able to call aggregate final functions repeatedly after aggregating more
651  * data onto the same transition value. This is not a behavior required by
652  * nodeAgg.c.
653  */
654 static void
656 {
657  WindowStatePerAgg peraggstate;
658  int wfuncno,
659  numaggs,
660  numaggs_restart,
661  i;
662  int64 aggregatedupto_nonrestarted;
663  MemoryContext oldContext;
664  ExprContext *econtext;
665  WindowObject agg_winobj;
666  TupleTableSlot *agg_row_slot;
667  TupleTableSlot *temp_slot;
668 
669  numaggs = winstate->numaggs;
670  if (numaggs == 0)
671  return; /* nothing to do */
672 
673  /* final output execution is in ps_ExprContext */
674  econtext = winstate->ss.ps.ps_ExprContext;
675  agg_winobj = winstate->agg_winobj;
676  agg_row_slot = winstate->agg_row_slot;
677  temp_slot = winstate->temp_slot_1;
678 
679  /*
680  * If the window's frame start clause is UNBOUNDED_PRECEDING and no
681  * exclusion clause is specified, then the window frame consists of a
682  * contiguous group of rows extending forward from the start of the
683  * partition, and rows only enter the frame, never exit it, as the current
684  * row advances forward. This makes it possible to use an incremental
685  * strategy for evaluating aggregates: we run the transition function for
686  * each row added to the frame, and run the final function whenever we
687  * need the current aggregate value. This is considerably more efficient
688  * than the naive approach of re-running the entire aggregate calculation
689  * for each current row. It does assume that the final function doesn't
690  * damage the running transition value, but we have the same assumption in
691  * nodeAgg.c too (when it rescans an existing hash table).
692  *
693  * If the frame start does sometimes move, we can still optimize as above
694  * whenever successive rows share the same frame head, but if the frame
695  * head moves beyond the previous head we try to remove those rows using
696  * the aggregate's inverse transition function. This function restores
697  * the aggregate's current state to what it would be if the removed row
698  * had never been aggregated in the first place. Inverse transition
699  * functions may optionally return NULL, indicating that the function was
700  * unable to remove the tuple from aggregation. If this happens, or if
701  * the aggregate doesn't have an inverse transition function at all, we
702  * must perform the aggregation all over again for all tuples within the
703  * new frame boundaries.
704  *
705  * If there's any exclusion clause, then we may have to aggregate over a
706  * non-contiguous set of rows, so we punt and recalculate for every row.
707  * (For some frame end choices, it might be that the frame is always
708  * contiguous anyway, but that's an optimization to investigate later.)
709  *
710  * In many common cases, multiple rows share the same frame and hence the
711  * same aggregate value. (In particular, if there's no ORDER BY in a RANGE
712  * window, then all rows are peers and so they all have window frame equal
713  * to the whole partition.) We optimize such cases by calculating the
714  * aggregate value once when we reach the first row of a peer group, and
715  * then returning the saved value for all subsequent rows.
716  *
717  * 'aggregatedupto' keeps track of the first row that has not yet been
718  * accumulated into the aggregate transition values. Whenever we start a
719  * new peer group, we accumulate forward to the end of the peer group.
720  */
721 
722  /*
723  * First, update the frame head position.
724  *
725  * The frame head should never move backwards, and the code below wouldn't
726  * cope if it did, so for safety we complain if it does.
727  */
728  update_frameheadpos(winstate);
729  if (winstate->frameheadpos < winstate->aggregatedbase)
730  elog(ERROR, "window frame head moved backward");
731 
732  /*
733  * If the frame didn't change compared to the previous row, we can re-use
734  * the result values that were previously saved at the bottom of this
735  * function. Since we don't know the current frame's end yet, this is not
736  * possible to check for fully. But if the frame end mode is UNBOUNDED
737  * FOLLOWING or CURRENT ROW, no exclusion clause is specified, and the
738  * current row lies within the previous row's frame, then the two frames'
739  * ends must coincide. Note that on the first row aggregatedbase ==
740  * aggregatedupto, meaning this test must fail, so we don't need to check
741  * the "there was no previous row" case explicitly here.
742  */
743  if (winstate->aggregatedbase == winstate->frameheadpos &&
746  !(winstate->frameOptions & FRAMEOPTION_EXCLUSION) &&
747  winstate->aggregatedbase <= winstate->currentpos &&
748  winstate->aggregatedupto > winstate->currentpos)
749  {
750  for (i = 0; i < numaggs; i++)
751  {
752  peraggstate = &winstate->peragg[i];
753  wfuncno = peraggstate->wfuncno;
754  econtext->ecxt_aggvalues[wfuncno] = peraggstate->resultValue;
755  econtext->ecxt_aggnulls[wfuncno] = peraggstate->resultValueIsNull;
756  }
757  return;
758  }
759 
760  /*----------
761  * Initialize restart flags.
762  *
763  * We restart the aggregation:
764  * - if we're processing the first row in the partition, or
765  * - if the frame's head moved and we cannot use an inverse
766  * transition function, or
767  * - we have an EXCLUSION clause, or
768  * - if the new frame doesn't overlap the old one
769  *
770  * Note that we don't strictly need to restart in the last case, but if
771  * we're going to remove all rows from the aggregation anyway, a restart
772  * surely is faster.
773  *----------
774  */
775  numaggs_restart = 0;
776  for (i = 0; i < numaggs; i++)
777  {
778  peraggstate = &winstate->peragg[i];
779  if (winstate->currentpos == 0 ||
780  (winstate->aggregatedbase != winstate->frameheadpos &&
781  !OidIsValid(peraggstate->invtransfn_oid)) ||
782  (winstate->frameOptions & FRAMEOPTION_EXCLUSION) ||
783  winstate->aggregatedupto <= winstate->frameheadpos)
784  {
785  peraggstate->restart = true;
786  numaggs_restart++;
787  }
788  else
789  peraggstate->restart = false;
790  }
791 
792  /*
793  * If we have any possibly-moving aggregates, attempt to advance
794  * aggregatedbase to match the frame's head by removing input rows that
795  * fell off the top of the frame from the aggregations. This can fail,
796  * i.e. advance_windowaggregate_base() can return false, in which case
797  * we'll restart that aggregate below.
798  */
799  while (numaggs_restart < numaggs &&
800  winstate->aggregatedbase < winstate->frameheadpos)
801  {
802  /*
803  * Fetch the next tuple of those being removed. This should never fail
804  * as we should have been here before.
805  */
806  if (!window_gettupleslot(agg_winobj, winstate->aggregatedbase,
807  temp_slot))
808  elog(ERROR, "could not re-fetch previously fetched frame row");
809 
810  /* Set tuple context for evaluation of aggregate arguments */
811  winstate->tmpcontext->ecxt_outertuple = temp_slot;
812 
813  /*
814  * Perform the inverse transition for each aggregate function in the
815  * window, unless it has already been marked as needing a restart.
816  */
817  for (i = 0; i < numaggs; i++)
818  {
819  bool ok;
820 
821  peraggstate = &winstate->peragg[i];
822  if (peraggstate->restart)
823  continue;
824 
825  wfuncno = peraggstate->wfuncno;
826  ok = advance_windowaggregate_base(winstate,
827  &winstate->perfunc[wfuncno],
828  peraggstate);
829  if (!ok)
830  {
831  /* Inverse transition function has failed, must restart */
832  peraggstate->restart = true;
833  numaggs_restart++;
834  }
835  }
836 
837  /* Reset per-input-tuple context after each tuple */
838  ResetExprContext(winstate->tmpcontext);
839 
840  /* And advance the aggregated-row state */
841  winstate->aggregatedbase++;
842  ExecClearTuple(temp_slot);
843  }
844 
845  /*
846  * If we successfully advanced the base rows of all the aggregates,
847  * aggregatedbase now equals frameheadpos; but if we failed for any, we
848  * must forcibly update aggregatedbase.
849  */
850  winstate->aggregatedbase = winstate->frameheadpos;
851 
852  /*
853  * If we created a mark pointer for aggregates, keep it pushed up to frame
854  * head, so that tuplestore can discard unnecessary rows.
855  */
856  if (agg_winobj->markptr >= 0)
857  WinSetMarkPosition(agg_winobj, winstate->frameheadpos);
858 
859  /*
860  * Now restart the aggregates that require it.
861  *
862  * We assume that aggregates using the shared context always restart if
863  * *any* aggregate restarts, and we may thus clean up the shared
864  * aggcontext if that is the case. Private aggcontexts are reset by
865  * initialize_windowaggregate() if their owning aggregate restarts. If we
866  * aren't restarting an aggregate, we need to free any previously saved
867  * result for it, else we'll leak memory.
868  */
869  if (numaggs_restart > 0)
871  for (i = 0; i < numaggs; i++)
872  {
873  peraggstate = &winstate->peragg[i];
874 
875  /* Aggregates using the shared ctx must restart if *any* agg does */
876  Assert(peraggstate->aggcontext != winstate->aggcontext ||
877  numaggs_restart == 0 ||
878  peraggstate->restart);
879 
880  if (peraggstate->restart)
881  {
882  wfuncno = peraggstate->wfuncno;
884  &winstate->perfunc[wfuncno],
885  peraggstate);
886  }
887  else if (!peraggstate->resultValueIsNull)
888  {
889  if (!peraggstate->resulttypeByVal)
890  pfree(DatumGetPointer(peraggstate->resultValue));
891  peraggstate->resultValue = (Datum) 0;
892  peraggstate->resultValueIsNull = true;
893  }
894  }
895 
896  /*
897  * Non-restarted aggregates now contain the rows between aggregatedbase
898  * (i.e., frameheadpos) and aggregatedupto, while restarted aggregates
899  * contain no rows. If there are any restarted aggregates, we must thus
900  * begin aggregating anew at frameheadpos, otherwise we may simply
901  * continue at aggregatedupto. We must remember the old value of
902  * aggregatedupto to know how long to skip advancing non-restarted
903  * aggregates. If we modify aggregatedupto, we must also clear
904  * agg_row_slot, per the loop invariant below.
905  */
906  aggregatedupto_nonrestarted = winstate->aggregatedupto;
907  if (numaggs_restart > 0 &&
908  winstate->aggregatedupto != winstate->frameheadpos)
909  {
910  winstate->aggregatedupto = winstate->frameheadpos;
911  ExecClearTuple(agg_row_slot);
912  }
913 
914  /*
915  * Advance until we reach a row not in frame (or end of partition).
916  *
917  * Note the loop invariant: agg_row_slot is either empty or holds the row
918  * at position aggregatedupto. We advance aggregatedupto after processing
919  * a row.
920  */
921  for (;;)
922  {
923  int ret;
924 
925  /* Fetch next row if we didn't already */
926  if (TupIsNull(agg_row_slot))
927  {
928  if (!window_gettupleslot(agg_winobj, winstate->aggregatedupto,
929  agg_row_slot))
930  break; /* must be end of partition */
931  }
932 
933  /*
934  * Exit loop if no more rows can be in frame. Skip aggregation if
935  * current row is not in frame but there might be more in the frame.
936  */
937  ret = row_is_in_frame(winstate, winstate->aggregatedupto, agg_row_slot);
938  if (ret < 0)
939  break;
940  if (ret == 0)
941  goto next_tuple;
942 
943  /* Set tuple context for evaluation of aggregate arguments */
944  winstate->tmpcontext->ecxt_outertuple = agg_row_slot;
945 
946  /* Accumulate row into the aggregates */
947  for (i = 0; i < numaggs; i++)
948  {
949  peraggstate = &winstate->peragg[i];
950 
951  /* Non-restarted aggs skip until aggregatedupto_nonrestarted */
952  if (!peraggstate->restart &&
953  winstate->aggregatedupto < aggregatedupto_nonrestarted)
954  continue;
955 
956  wfuncno = peraggstate->wfuncno;
957  advance_windowaggregate(winstate,
958  &winstate->perfunc[wfuncno],
959  peraggstate);
960  }
961 
962 next_tuple:
963  /* Reset per-input-tuple context after each tuple */
964  ResetExprContext(winstate->tmpcontext);
965 
966  /* And advance the aggregated-row state */
967  winstate->aggregatedupto++;
968  ExecClearTuple(agg_row_slot);
969  }
970 
971  /* The frame's end is not supposed to move backwards, ever */
972  Assert(aggregatedupto_nonrestarted <= winstate->aggregatedupto);
973 
974  /*
975  * finalize aggregates and fill result/isnull fields.
976  */
977  for (i = 0; i < numaggs; i++)
978  {
979  Datum *result;
980  bool *isnull;
981 
982  peraggstate = &winstate->peragg[i];
983  wfuncno = peraggstate->wfuncno;
984  result = &econtext->ecxt_aggvalues[wfuncno];
985  isnull = &econtext->ecxt_aggnulls[wfuncno];
986  finalize_windowaggregate(winstate,
987  &winstate->perfunc[wfuncno],
988  peraggstate,
989  result, isnull);
990 
991  /*
992  * save the result in case next row shares the same frame.
993  *
994  * XXX in some framing modes, eg ROWS/END_CURRENT_ROW, we can know in
995  * advance that the next row can't possibly share the same frame. Is
996  * it worth detecting that and skipping this code?
997  */
998  if (!peraggstate->resulttypeByVal && !*isnull)
999  {
1000  oldContext = MemoryContextSwitchTo(peraggstate->aggcontext);
1001  peraggstate->resultValue =
1002  datumCopy(*result,
1003  peraggstate->resulttypeByVal,
1004  peraggstate->resulttypeLen);
1005  MemoryContextSwitchTo(oldContext);
1006  }
1007  else
1008  {
1009  peraggstate->resultValue = *result;
1010  }
1011  peraggstate->resultValueIsNull = *isnull;
1012  }
1013 }
1014 
1015 /*
1016  * eval_windowfunction
1017  *
1018  * Arguments of window functions are not evaluated here, because a window
1019  * function can need random access to arbitrary rows in the partition.
1020  * The window function uses the special WinGetFuncArgInPartition and
1021  * WinGetFuncArgInFrame functions to evaluate the arguments for the rows
1022  * it wants.
1023  */
1024 static void
1026  Datum *result, bool *isnull)
1027 {
1028  LOCAL_FCINFO(fcinfo, FUNC_MAX_ARGS);
1029  MemoryContext oldContext;
1030 
1032 
1033  /*
1034  * We don't pass any normal arguments to a window function, but we do pass
1035  * it the number of arguments, in order to permit window function
1036  * implementations to support varying numbers of arguments. The real info
1037  * goes through the WindowObject, which is passed via fcinfo->context.
1038  */
1039  InitFunctionCallInfoData(*fcinfo, &(perfuncstate->flinfo),
1040  perfuncstate->numArguments,
1041  perfuncstate->winCollation,
1042  (void *) perfuncstate->winobj, NULL);
1043  /* Just in case, make all the regular argument slots be null */
1044  for (int argno = 0; argno < perfuncstate->numArguments; argno++)
1045  fcinfo->args[argno].isnull = true;
1046  /* Window functions don't have a current aggregate context, either */
1047  winstate->curaggcontext = NULL;
1048 
1049  *result = FunctionCallInvoke(fcinfo);
1050  *isnull = fcinfo->isnull;
1051 
1052  /*
1053  * The window function might have returned a pass-by-ref result that's
1054  * just a pointer into one of the WindowObject's temporary slots. That's
1055  * not a problem if it's the only window function using the WindowObject;
1056  * but if there's more than one function, we'd better copy the result to
1057  * ensure it's not clobbered by later window functions.
1058  */
1059  if (!perfuncstate->resulttypeByVal && !fcinfo->isnull &&
1060  winstate->numfuncs > 1)
1061  *result = datumCopy(*result,
1062  perfuncstate->resulttypeByVal,
1063  perfuncstate->resulttypeLen);
1064 
1065  MemoryContextSwitchTo(oldContext);
1066 }
1067 
1068 /*
1069  * begin_partition
1070  * Start buffering rows of the next partition.
1071  */
1072 static void
1074 {
1075  WindowAgg *node = (WindowAgg *) winstate->ss.ps.plan;
1076  PlanState *outerPlan = outerPlanState(winstate);
1077  int frameOptions = winstate->frameOptions;
1078  int numfuncs = winstate->numfuncs;
1079  int i;
1080 
1081  winstate->partition_spooled = false;
1082  winstate->framehead_valid = false;
1083  winstate->frametail_valid = false;
1084  winstate->grouptail_valid = false;
1085  winstate->spooled_rows = 0;
1086  winstate->currentpos = 0;
1087  winstate->frameheadpos = 0;
1088  winstate->frametailpos = 0;
1089  winstate->currentgroup = 0;
1090  winstate->frameheadgroup = 0;
1091  winstate->frametailgroup = 0;
1092  winstate->groupheadpos = 0;
1093  winstate->grouptailpos = -1; /* see update_grouptailpos */
1094  ExecClearTuple(winstate->agg_row_slot);
1095  if (winstate->framehead_slot)
1096  ExecClearTuple(winstate->framehead_slot);
1097  if (winstate->frametail_slot)
1098  ExecClearTuple(winstate->frametail_slot);
1099 
1100  /*
1101  * If this is the very first partition, we need to fetch the first input
1102  * row to store in first_part_slot.
1103  */
1104  if (TupIsNull(winstate->first_part_slot))
1105  {
1106  TupleTableSlot *outerslot = ExecProcNode(outerPlan);
1107 
1108  if (!TupIsNull(outerslot))
1109  ExecCopySlot(winstate->first_part_slot, outerslot);
1110  else
1111  {
1112  /* outer plan is empty, so we have nothing to do */
1113  winstate->partition_spooled = true;
1114  winstate->more_partitions = false;
1115  return;
1116  }
1117  }
1118 
1119  /* Create new tuplestore for this partition */
1120  winstate->buffer = tuplestore_begin_heap(false, false, work_mem);
1121 
1122  /*
1123  * Set up read pointers for the tuplestore. The current pointer doesn't
1124  * need BACKWARD capability, but the per-window-function read pointers do,
1125  * and the aggregate pointer does if we might need to restart aggregation.
1126  */
1127  winstate->current_ptr = 0; /* read pointer 0 is pre-allocated */
1128 
1129  /* reset default REWIND capability bit for current ptr */
1130  tuplestore_set_eflags(winstate->buffer, 0);
1131 
1132  /* create read pointers for aggregates, if needed */
1133  if (winstate->numaggs > 0)
1134  {
1135  WindowObject agg_winobj = winstate->agg_winobj;
1136  int readptr_flags = 0;
1137 
1138  /*
1139  * If the frame head is potentially movable, or we have an EXCLUSION
1140  * clause, we might need to restart aggregation ...
1141  */
1142  if (!(frameOptions & FRAMEOPTION_START_UNBOUNDED_PRECEDING) ||
1143  (frameOptions & FRAMEOPTION_EXCLUSION))
1144  {
1145  /* ... so create a mark pointer to track the frame head */
1146  agg_winobj->markptr = tuplestore_alloc_read_pointer(winstate->buffer, 0);
1147  /* and the read pointer will need BACKWARD capability */
1148  readptr_flags |= EXEC_FLAG_BACKWARD;
1149  }
1150 
1151  agg_winobj->readptr = tuplestore_alloc_read_pointer(winstate->buffer,
1152  readptr_flags);
1153  agg_winobj->markpos = -1;
1154  agg_winobj->seekpos = -1;
1155 
1156  /* Also reset the row counters for aggregates */
1157  winstate->aggregatedbase = 0;
1158  winstate->aggregatedupto = 0;
1159  }
1160 
1161  /* create mark and read pointers for each real window function */
1162  for (i = 0; i < numfuncs; i++)
1163  {
1164  WindowStatePerFunc perfuncstate = &(winstate->perfunc[i]);
1165 
1166  if (!perfuncstate->plain_agg)
1167  {
1168  WindowObject winobj = perfuncstate->winobj;
1169 
1170  winobj->markptr = tuplestore_alloc_read_pointer(winstate->buffer,
1171  0);
1172  winobj->readptr = tuplestore_alloc_read_pointer(winstate->buffer,
1174  winobj->markpos = -1;
1175  winobj->seekpos = -1;
1176  }
1177  }
1178 
1179  /*
1180  * If we are in RANGE or GROUPS mode, then determining frame boundaries
1181  * requires physical access to the frame endpoint rows, except in certain
1182  * degenerate cases. We create read pointers to point to those rows, to
1183  * simplify access and ensure that the tuplestore doesn't discard the
1184  * endpoint rows prematurely. (Must create pointers in exactly the same
1185  * cases that update_frameheadpos and update_frametailpos need them.)
1186  */
1187  winstate->framehead_ptr = winstate->frametail_ptr = -1; /* if not used */
1188 
1189  if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
1190  {
1191  if (((frameOptions & FRAMEOPTION_START_CURRENT_ROW) &&
1192  node->ordNumCols != 0) ||
1193  (frameOptions & FRAMEOPTION_START_OFFSET))
1194  winstate->framehead_ptr =
1195  tuplestore_alloc_read_pointer(winstate->buffer, 0);
1196  if (((frameOptions & FRAMEOPTION_END_CURRENT_ROW) &&
1197  node->ordNumCols != 0) ||
1198  (frameOptions & FRAMEOPTION_END_OFFSET))
1199  winstate->frametail_ptr =
1200  tuplestore_alloc_read_pointer(winstate->buffer, 0);
1201  }
1202 
1203  /*
1204  * If we have an exclusion clause that requires knowing the boundaries of
1205  * the current row's peer group, we create a read pointer to track the
1206  * tail position of the peer group (i.e., first row of the next peer
1207  * group). The head position does not require its own pointer because we
1208  * maintain that as a side effect of advancing the current row.
1209  */
1210  winstate->grouptail_ptr = -1;
1211 
1212  if ((frameOptions & (FRAMEOPTION_EXCLUDE_GROUP |
1214  node->ordNumCols != 0)
1215  {
1216  winstate->grouptail_ptr =
1217  tuplestore_alloc_read_pointer(winstate->buffer, 0);
1218  }
1219 
1220  /*
1221  * Store the first tuple into the tuplestore (it's always available now;
1222  * we either read it above, or saved it at the end of previous partition)
1223  */
1224  tuplestore_puttupleslot(winstate->buffer, winstate->first_part_slot);
1225  winstate->spooled_rows++;
1226 }
1227 
1228 /*
1229  * Read tuples from the outer node, up to and including position 'pos', and
1230  * store them into the tuplestore. If pos is -1, reads the whole partition.
1231  */
1232 static void
1233 spool_tuples(WindowAggState *winstate, int64 pos)
1234 {
1235  WindowAgg *node = (WindowAgg *) winstate->ss.ps.plan;
1237  TupleTableSlot *outerslot;
1238  MemoryContext oldcontext;
1239 
1240  if (!winstate->buffer)
1241  return; /* just a safety check */
1242  if (winstate->partition_spooled)
1243  return; /* whole partition done already */
1244 
1245  /*
1246  * When in pass-through mode we can just exhaust all tuples in the current
1247  * partition. We don't need these tuples for any further window function
1248  * evaluation, however, we do need to keep them around if we're not the
1249  * top-level window as another WindowAgg node above must see these.
1250  */
1251  if (winstate->status != WINDOWAGG_RUN)
1252  {
1253  Assert(winstate->status == WINDOWAGG_PASSTHROUGH ||
1254  winstate->status == WINDOWAGG_PASSTHROUGH_STRICT);
1255 
1256  pos = -1;
1257  }
1258 
1259  /*
1260  * If the tuplestore has spilled to disk, alternate reading and writing
1261  * becomes quite expensive due to frequent buffer flushes. It's cheaper
1262  * to force the entire partition to get spooled in one go.
1263  *
1264  * XXX this is a horrid kluge --- it'd be better to fix the performance
1265  * problem inside tuplestore. FIXME
1266  */
1267  else if (!tuplestore_in_memory(winstate->buffer))
1268  pos = -1;
1269 
1270  outerPlan = outerPlanState(winstate);
1271 
1272  /* Must be in query context to call outerplan */
1274 
1275  while (winstate->spooled_rows <= pos || pos == -1)
1276  {
1277  outerslot = ExecProcNode(outerPlan);
1278  if (TupIsNull(outerslot))
1279  {
1280  /* reached the end of the last partition */
1281  winstate->partition_spooled = true;
1282  winstate->more_partitions = false;
1283  break;
1284  }
1285 
1286  if (node->partNumCols > 0)
1287  {
1288  ExprContext *econtext = winstate->tmpcontext;
1289 
1290  econtext->ecxt_innertuple = winstate->first_part_slot;
1291  econtext->ecxt_outertuple = outerslot;
1292 
1293  /* Check if this tuple still belongs to the current partition */
1294  if (!ExecQualAndReset(winstate->partEqfunction, econtext))
1295  {
1296  /*
1297  * end of partition; copy the tuple for the next cycle.
1298  */
1299  ExecCopySlot(winstate->first_part_slot, outerslot);
1300  winstate->partition_spooled = true;
1301  winstate->more_partitions = true;
1302  break;
1303  }
1304  }
1305 
1306  /*
1307  * Remember the tuple unless we're the top-level window and we're in
1308  * pass-through mode.
1309  */
1310  if (winstate->status != WINDOWAGG_PASSTHROUGH_STRICT)
1311  {
1312  /* Still in partition, so save it into the tuplestore */
1313  tuplestore_puttupleslot(winstate->buffer, outerslot);
1314  winstate->spooled_rows++;
1315  }
1316  }
1317 
1318  MemoryContextSwitchTo(oldcontext);
1319 }
1320 
1321 /*
1322  * release_partition
1323  * clear information kept within a partition, including
1324  * tuplestore and aggregate results.
1325  */
1326 static void
1328 {
1329  int i;
1330 
1331  for (i = 0; i < winstate->numfuncs; i++)
1332  {
1333  WindowStatePerFunc perfuncstate = &(winstate->perfunc[i]);
1334 
1335  /* Release any partition-local state of this window function */
1336  if (perfuncstate->winobj)
1337  perfuncstate->winobj->localmem = NULL;
1338  }
1339 
1340  /*
1341  * Release all partition-local memory (in particular, any partition-local
1342  * state that we might have trashed our pointers to in the above loop, and
1343  * any aggregate temp data). We don't rely on retail pfree because some
1344  * aggregates might have allocated data we don't have direct pointers to.
1345  */
1348  for (i = 0; i < winstate->numaggs; i++)
1349  {
1350  if (winstate->peragg[i].aggcontext != winstate->aggcontext)
1352  }
1353 
1354  if (winstate->buffer)
1355  tuplestore_end(winstate->buffer);
1356  winstate->buffer = NULL;
1357  winstate->partition_spooled = false;
1358 }
1359 
1360 /*
1361  * row_is_in_frame
1362  * Determine whether a row is in the current row's window frame according
1363  * to our window framing rule
1364  *
1365  * The caller must have already determined that the row is in the partition
1366  * and fetched it into a slot. This function just encapsulates the framing
1367  * rules.
1368  *
1369  * Returns:
1370  * -1, if the row is out of frame and no succeeding rows can be in frame
1371  * 0, if the row is out of frame but succeeding rows might be in frame
1372  * 1, if the row is in frame
1373  *
1374  * May clobber winstate->temp_slot_2.
1375  */
1376 static int
1377 row_is_in_frame(WindowAggState *winstate, int64 pos, TupleTableSlot *slot)
1378 {
1379  int frameOptions = winstate->frameOptions;
1380 
1381  Assert(pos >= 0); /* else caller error */
1382 
1383  /*
1384  * First, check frame starting conditions. We might as well delegate this
1385  * to update_frameheadpos always; it doesn't add any notable cost.
1386  */
1387  update_frameheadpos(winstate);
1388  if (pos < winstate->frameheadpos)
1389  return 0;
1390 
1391  /*
1392  * Okay so far, now check frame ending conditions. Here, we avoid calling
1393  * update_frametailpos in simple cases, so as not to spool tuples further
1394  * ahead than necessary.
1395  */
1396  if (frameOptions & FRAMEOPTION_END_CURRENT_ROW)
1397  {
1398  if (frameOptions & FRAMEOPTION_ROWS)
1399  {
1400  /* rows after current row are out of frame */
1401  if (pos > winstate->currentpos)
1402  return -1;
1403  }
1404  else if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
1405  {
1406  /* following row that is not peer is out of frame */
1407  if (pos > winstate->currentpos &&
1408  !are_peers(winstate, slot, winstate->ss.ss_ScanTupleSlot))
1409  return -1;
1410  }
1411  else
1412  Assert(false);
1413  }
1414  else if (frameOptions & FRAMEOPTION_END_OFFSET)
1415  {
1416  if (frameOptions & FRAMEOPTION_ROWS)
1417  {
1418  int64 offset = DatumGetInt64(winstate->endOffsetValue);
1419 
1420  /* rows after current row + offset are out of frame */
1421  if (frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
1422  offset = -offset;
1423 
1424  if (pos > winstate->currentpos + offset)
1425  return -1;
1426  }
1427  else if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
1428  {
1429  /* hard cases, so delegate to update_frametailpos */
1430  update_frametailpos(winstate);
1431  if (pos >= winstate->frametailpos)
1432  return -1;
1433  }
1434  else
1435  Assert(false);
1436  }
1437 
1438  /* Check exclusion clause */
1439  if (frameOptions & FRAMEOPTION_EXCLUDE_CURRENT_ROW)
1440  {
1441  if (pos == winstate->currentpos)
1442  return 0;
1443  }
1444  else if ((frameOptions & FRAMEOPTION_EXCLUDE_GROUP) ||
1445  ((frameOptions & FRAMEOPTION_EXCLUDE_TIES) &&
1446  pos != winstate->currentpos))
1447  {
1448  WindowAgg *node = (WindowAgg *) winstate->ss.ps.plan;
1449 
1450  /* If no ORDER BY, all rows are peers with each other */
1451  if (node->ordNumCols == 0)
1452  return 0;
1453  /* Otherwise, check the group boundaries */
1454  if (pos >= winstate->groupheadpos)
1455  {
1456  update_grouptailpos(winstate);
1457  if (pos < winstate->grouptailpos)
1458  return 0;
1459  }
1460  }
1461 
1462  /* If we get here, it's in frame */
1463  return 1;
1464 }
1465 
1466 /*
1467  * update_frameheadpos
1468  * make frameheadpos valid for the current row
1469  *
1470  * Note that frameheadpos is computed without regard for any window exclusion
1471  * clause; the current row and/or its peers are considered part of the frame
1472  * for this purpose even if they must be excluded later.
1473  *
1474  * May clobber winstate->temp_slot_2.
1475  */
1476 static void
1478 {
1479  WindowAgg *node = (WindowAgg *) winstate->ss.ps.plan;
1480  int frameOptions = winstate->frameOptions;
1481  MemoryContext oldcontext;
1482 
1483  if (winstate->framehead_valid)
1484  return; /* already known for current row */
1485 
1486  /* We may be called in a short-lived context */
1488 
1489  if (frameOptions & FRAMEOPTION_START_UNBOUNDED_PRECEDING)
1490  {
1491  /* In UNBOUNDED PRECEDING mode, frame head is always row 0 */
1492  winstate->frameheadpos = 0;
1493  winstate->framehead_valid = true;
1494  }
1495  else if (frameOptions & FRAMEOPTION_START_CURRENT_ROW)
1496  {
1497  if (frameOptions & FRAMEOPTION_ROWS)
1498  {
1499  /* In ROWS mode, frame head is the same as current */
1500  winstate->frameheadpos = winstate->currentpos;
1501  winstate->framehead_valid = true;
1502  }
1503  else if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
1504  {
1505  /* If no ORDER BY, all rows are peers with each other */
1506  if (node->ordNumCols == 0)
1507  {
1508  winstate->frameheadpos = 0;
1509  winstate->framehead_valid = true;
1510  MemoryContextSwitchTo(oldcontext);
1511  return;
1512  }
1513 
1514  /*
1515  * In RANGE or GROUPS START_CURRENT_ROW mode, frame head is the
1516  * first row that is a peer of current row. We keep a copy of the
1517  * last-known frame head row in framehead_slot, and advance as
1518  * necessary. Note that if we reach end of partition, we will
1519  * leave frameheadpos = end+1 and framehead_slot empty.
1520  */
1522  winstate->framehead_ptr);
1523  if (winstate->frameheadpos == 0 &&
1524  TupIsNull(winstate->framehead_slot))
1525  {
1526  /* fetch first row into framehead_slot, if we didn't already */
1527  if (!tuplestore_gettupleslot(winstate->buffer, true, true,
1528  winstate->framehead_slot))
1529  elog(ERROR, "unexpected end of tuplestore");
1530  }
1531 
1532  while (!TupIsNull(winstate->framehead_slot))
1533  {
1534  if (are_peers(winstate, winstate->framehead_slot,
1535  winstate->ss.ss_ScanTupleSlot))
1536  break; /* this row is the correct frame head */
1537  /* Note we advance frameheadpos even if the fetch fails */
1538  winstate->frameheadpos++;
1539  spool_tuples(winstate, winstate->frameheadpos);
1540  if (!tuplestore_gettupleslot(winstate->buffer, true, true,
1541  winstate->framehead_slot))
1542  break; /* end of partition */
1543  }
1544  winstate->framehead_valid = true;
1545  }
1546  else
1547  Assert(false);
1548  }
1549  else if (frameOptions & FRAMEOPTION_START_OFFSET)
1550  {
1551  if (frameOptions & FRAMEOPTION_ROWS)
1552  {
1553  /* In ROWS mode, bound is physically n before/after current */
1554  int64 offset = DatumGetInt64(winstate->startOffsetValue);
1555 
1556  if (frameOptions & FRAMEOPTION_START_OFFSET_PRECEDING)
1557  offset = -offset;
1558 
1559  winstate->frameheadpos = winstate->currentpos + offset;
1560  /* frame head can't go before first row */
1561  if (winstate->frameheadpos < 0)
1562  winstate->frameheadpos = 0;
1563  else if (winstate->frameheadpos > winstate->currentpos + 1)
1564  {
1565  /* make sure frameheadpos is not past end of partition */
1566  spool_tuples(winstate, winstate->frameheadpos - 1);
1567  if (winstate->frameheadpos > winstate->spooled_rows)
1568  winstate->frameheadpos = winstate->spooled_rows;
1569  }
1570  winstate->framehead_valid = true;
1571  }
1572  else if (frameOptions & FRAMEOPTION_RANGE)
1573  {
1574  /*
1575  * In RANGE START_OFFSET mode, frame head is the first row that
1576  * satisfies the in_range constraint relative to the current row.
1577  * We keep a copy of the last-known frame head row in
1578  * framehead_slot, and advance as necessary. Note that if we
1579  * reach end of partition, we will leave frameheadpos = end+1 and
1580  * framehead_slot empty.
1581  */
1582  int sortCol = node->ordColIdx[0];
1583  bool sub,
1584  less;
1585 
1586  /* We must have an ordering column */
1587  Assert(node->ordNumCols == 1);
1588 
1589  /* Precompute flags for in_range checks */
1590  if (frameOptions & FRAMEOPTION_START_OFFSET_PRECEDING)
1591  sub = true; /* subtract startOffset from current row */
1592  else
1593  sub = false; /* add it */
1594  less = false; /* normally, we want frame head >= sum */
1595  /* If sort order is descending, flip both flags */
1596  if (!winstate->inRangeAsc)
1597  {
1598  sub = !sub;
1599  less = true;
1600  }
1601 
1603  winstate->framehead_ptr);
1604  if (winstate->frameheadpos == 0 &&
1605  TupIsNull(winstate->framehead_slot))
1606  {
1607  /* fetch first row into framehead_slot, if we didn't already */
1608  if (!tuplestore_gettupleslot(winstate->buffer, true, true,
1609  winstate->framehead_slot))
1610  elog(ERROR, "unexpected end of tuplestore");
1611  }
1612 
1613  while (!TupIsNull(winstate->framehead_slot))
1614  {
1615  Datum headval,
1616  currval;
1617  bool headisnull,
1618  currisnull;
1619 
1620  headval = slot_getattr(winstate->framehead_slot, sortCol,
1621  &headisnull);
1622  currval = slot_getattr(winstate->ss.ss_ScanTupleSlot, sortCol,
1623  &currisnull);
1624  if (headisnull || currisnull)
1625  {
1626  /* order of the rows depends only on nulls_first */
1627  if (winstate->inRangeNullsFirst)
1628  {
1629  /* advance head if head is null and curr is not */
1630  if (!headisnull || currisnull)
1631  break;
1632  }
1633  else
1634  {
1635  /* advance head if head is not null and curr is null */
1636  if (headisnull || !currisnull)
1637  break;
1638  }
1639  }
1640  else
1641  {
1643  winstate->inRangeColl,
1644  headval,
1645  currval,
1646  winstate->startOffsetValue,
1647  BoolGetDatum(sub),
1648  BoolGetDatum(less))))
1649  break; /* this row is the correct frame head */
1650  }
1651  /* Note we advance frameheadpos even if the fetch fails */
1652  winstate->frameheadpos++;
1653  spool_tuples(winstate, winstate->frameheadpos);
1654  if (!tuplestore_gettupleslot(winstate->buffer, true, true,
1655  winstate->framehead_slot))
1656  break; /* end of partition */
1657  }
1658  winstate->framehead_valid = true;
1659  }
1660  else if (frameOptions & FRAMEOPTION_GROUPS)
1661  {
1662  /*
1663  * In GROUPS START_OFFSET mode, frame head is the first row of the
1664  * first peer group whose number satisfies the offset constraint.
1665  * We keep a copy of the last-known frame head row in
1666  * framehead_slot, and advance as necessary. Note that if we
1667  * reach end of partition, we will leave frameheadpos = end+1 and
1668  * framehead_slot empty.
1669  */
1670  int64 offset = DatumGetInt64(winstate->startOffsetValue);
1671  int64 minheadgroup;
1672 
1673  if (frameOptions & FRAMEOPTION_START_OFFSET_PRECEDING)
1674  minheadgroup = winstate->currentgroup - offset;
1675  else
1676  minheadgroup = winstate->currentgroup + offset;
1677 
1679  winstate->framehead_ptr);
1680  if (winstate->frameheadpos == 0 &&
1681  TupIsNull(winstate->framehead_slot))
1682  {
1683  /* fetch first row into framehead_slot, if we didn't already */
1684  if (!tuplestore_gettupleslot(winstate->buffer, true, true,
1685  winstate->framehead_slot))
1686  elog(ERROR, "unexpected end of tuplestore");
1687  }
1688 
1689  while (!TupIsNull(winstate->framehead_slot))
1690  {
1691  if (winstate->frameheadgroup >= minheadgroup)
1692  break; /* this row is the correct frame head */
1693  ExecCopySlot(winstate->temp_slot_2, winstate->framehead_slot);
1694  /* Note we advance frameheadpos even if the fetch fails */
1695  winstate->frameheadpos++;
1696  spool_tuples(winstate, winstate->frameheadpos);
1697  if (!tuplestore_gettupleslot(winstate->buffer, true, true,
1698  winstate->framehead_slot))
1699  break; /* end of partition */
1700  if (!are_peers(winstate, winstate->temp_slot_2,
1701  winstate->framehead_slot))
1702  winstate->frameheadgroup++;
1703  }
1704  ExecClearTuple(winstate->temp_slot_2);
1705  winstate->framehead_valid = true;
1706  }
1707  else
1708  Assert(false);
1709  }
1710  else
1711  Assert(false);
1712 
1713  MemoryContextSwitchTo(oldcontext);
1714 }
1715 
1716 /*
1717  * update_frametailpos
1718  * make frametailpos valid for the current row
1719  *
1720  * Note that frametailpos is computed without regard for any window exclusion
1721  * clause; the current row and/or its peers are considered part of the frame
1722  * for this purpose even if they must be excluded later.
1723  *
1724  * May clobber winstate->temp_slot_2.
1725  */
1726 static void
1728 {
1729  WindowAgg *node = (WindowAgg *) winstate->ss.ps.plan;
1730  int frameOptions = winstate->frameOptions;
1731  MemoryContext oldcontext;
1732 
1733  if (winstate->frametail_valid)
1734  return; /* already known for current row */
1735 
1736  /* We may be called in a short-lived context */
1738 
1739  if (frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING)
1740  {
1741  /* In UNBOUNDED FOLLOWING mode, all partition rows are in frame */
1742  spool_tuples(winstate, -1);
1743  winstate->frametailpos = winstate->spooled_rows;
1744  winstate->frametail_valid = true;
1745  }
1746  else if (frameOptions & FRAMEOPTION_END_CURRENT_ROW)
1747  {
1748  if (frameOptions & FRAMEOPTION_ROWS)
1749  {
1750  /* In ROWS mode, exactly the rows up to current are in frame */
1751  winstate->frametailpos = winstate->currentpos + 1;
1752  winstate->frametail_valid = true;
1753  }
1754  else if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
1755  {
1756  /* If no ORDER BY, all rows are peers with each other */
1757  if (node->ordNumCols == 0)
1758  {
1759  spool_tuples(winstate, -1);
1760  winstate->frametailpos = winstate->spooled_rows;
1761  winstate->frametail_valid = true;
1762  MemoryContextSwitchTo(oldcontext);
1763  return;
1764  }
1765 
1766  /*
1767  * In RANGE or GROUPS END_CURRENT_ROW mode, frame end is the last
1768  * row that is a peer of current row, frame tail is the row after
1769  * that (if any). We keep a copy of the last-known frame tail row
1770  * in frametail_slot, and advance as necessary. Note that if we
1771  * reach end of partition, we will leave frametailpos = end+1 and
1772  * frametail_slot empty.
1773  */
1775  winstate->frametail_ptr);
1776  if (winstate->frametailpos == 0 &&
1777  TupIsNull(winstate->frametail_slot))
1778  {
1779  /* fetch first row into frametail_slot, if we didn't already */
1780  if (!tuplestore_gettupleslot(winstate->buffer, true, true,
1781  winstate->frametail_slot))
1782  elog(ERROR, "unexpected end of tuplestore");
1783  }
1784 
1785  while (!TupIsNull(winstate->frametail_slot))
1786  {
1787  if (winstate->frametailpos > winstate->currentpos &&
1788  !are_peers(winstate, winstate->frametail_slot,
1789  winstate->ss.ss_ScanTupleSlot))
1790  break; /* this row is the frame tail */
1791  /* Note we advance frametailpos even if the fetch fails */
1792  winstate->frametailpos++;
1793  spool_tuples(winstate, winstate->frametailpos);
1794  if (!tuplestore_gettupleslot(winstate->buffer, true, true,
1795  winstate->frametail_slot))
1796  break; /* end of partition */
1797  }
1798  winstate->frametail_valid = true;
1799  }
1800  else
1801  Assert(false);
1802  }
1803  else if (frameOptions & FRAMEOPTION_END_OFFSET)
1804  {
1805  if (frameOptions & FRAMEOPTION_ROWS)
1806  {
1807  /* In ROWS mode, bound is physically n before/after current */
1808  int64 offset = DatumGetInt64(winstate->endOffsetValue);
1809 
1810  if (frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
1811  offset = -offset;
1812 
1813  winstate->frametailpos = winstate->currentpos + offset + 1;
1814  /* smallest allowable value of frametailpos is 0 */
1815  if (winstate->frametailpos < 0)
1816  winstate->frametailpos = 0;
1817  else if (winstate->frametailpos > winstate->currentpos + 1)
1818  {
1819  /* make sure frametailpos is not past end of partition */
1820  spool_tuples(winstate, winstate->frametailpos - 1);
1821  if (winstate->frametailpos > winstate->spooled_rows)
1822  winstate->frametailpos = winstate->spooled_rows;
1823  }
1824  winstate->frametail_valid = true;
1825  }
1826  else if (frameOptions & FRAMEOPTION_RANGE)
1827  {
1828  /*
1829  * In RANGE END_OFFSET mode, frame end is the last row that
1830  * satisfies the in_range constraint relative to the current row,
1831  * frame tail is the row after that (if any). We keep a copy of
1832  * the last-known frame tail row in frametail_slot, and advance as
1833  * necessary. Note that if we reach end of partition, we will
1834  * leave frametailpos = end+1 and frametail_slot empty.
1835  */
1836  int sortCol = node->ordColIdx[0];
1837  bool sub,
1838  less;
1839 
1840  /* We must have an ordering column */
1841  Assert(node->ordNumCols == 1);
1842 
1843  /* Precompute flags for in_range checks */
1844  if (frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
1845  sub = true; /* subtract endOffset from current row */
1846  else
1847  sub = false; /* add it */
1848  less = true; /* normally, we want frame tail <= sum */
1849  /* If sort order is descending, flip both flags */
1850  if (!winstate->inRangeAsc)
1851  {
1852  sub = !sub;
1853  less = false;
1854  }
1855 
1857  winstate->frametail_ptr);
1858  if (winstate->frametailpos == 0 &&
1859  TupIsNull(winstate->frametail_slot))
1860  {
1861  /* fetch first row into frametail_slot, if we didn't already */
1862  if (!tuplestore_gettupleslot(winstate->buffer, true, true,
1863  winstate->frametail_slot))
1864  elog(ERROR, "unexpected end of tuplestore");
1865  }
1866 
1867  while (!TupIsNull(winstate->frametail_slot))
1868  {
1869  Datum tailval,
1870  currval;
1871  bool tailisnull,
1872  currisnull;
1873 
1874  tailval = slot_getattr(winstate->frametail_slot, sortCol,
1875  &tailisnull);
1876  currval = slot_getattr(winstate->ss.ss_ScanTupleSlot, sortCol,
1877  &currisnull);
1878  if (tailisnull || currisnull)
1879  {
1880  /* order of the rows depends only on nulls_first */
1881  if (winstate->inRangeNullsFirst)
1882  {
1883  /* advance tail if tail is null or curr is not */
1884  if (!tailisnull)
1885  break;
1886  }
1887  else
1888  {
1889  /* advance tail if tail is not null or curr is null */
1890  if (!currisnull)
1891  break;
1892  }
1893  }
1894  else
1895  {
1897  winstate->inRangeColl,
1898  tailval,
1899  currval,
1900  winstate->endOffsetValue,
1901  BoolGetDatum(sub),
1902  BoolGetDatum(less))))
1903  break; /* this row is the correct frame tail */
1904  }
1905  /* Note we advance frametailpos even if the fetch fails */
1906  winstate->frametailpos++;
1907  spool_tuples(winstate, winstate->frametailpos);
1908  if (!tuplestore_gettupleslot(winstate->buffer, true, true,
1909  winstate->frametail_slot))
1910  break; /* end of partition */
1911  }
1912  winstate->frametail_valid = true;
1913  }
1914  else if (frameOptions & FRAMEOPTION_GROUPS)
1915  {
1916  /*
1917  * In GROUPS END_OFFSET mode, frame end is the last row of the
1918  * last peer group whose number satisfies the offset constraint,
1919  * and frame tail is the row after that (if any). We keep a copy
1920  * of the last-known frame tail row in frametail_slot, and advance
1921  * as necessary. Note that if we reach end of partition, we will
1922  * leave frametailpos = end+1 and frametail_slot empty.
1923  */
1924  int64 offset = DatumGetInt64(winstate->endOffsetValue);
1925  int64 maxtailgroup;
1926 
1927  if (frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
1928  maxtailgroup = winstate->currentgroup - offset;
1929  else
1930  maxtailgroup = winstate->currentgroup + offset;
1931 
1933  winstate->frametail_ptr);
1934  if (winstate->frametailpos == 0 &&
1935  TupIsNull(winstate->frametail_slot))
1936  {
1937  /* fetch first row into frametail_slot, if we didn't already */
1938  if (!tuplestore_gettupleslot(winstate->buffer, true, true,
1939  winstate->frametail_slot))
1940  elog(ERROR, "unexpected end of tuplestore");
1941  }
1942 
1943  while (!TupIsNull(winstate->frametail_slot))
1944  {
1945  if (winstate->frametailgroup > maxtailgroup)
1946  break; /* this row is the correct frame tail */
1947  ExecCopySlot(winstate->temp_slot_2, winstate->frametail_slot);
1948  /* Note we advance frametailpos even if the fetch fails */
1949  winstate->frametailpos++;
1950  spool_tuples(winstate, winstate->frametailpos);
1951  if (!tuplestore_gettupleslot(winstate->buffer, true, true,
1952  winstate->frametail_slot))
1953  break; /* end of partition */
1954  if (!are_peers(winstate, winstate->temp_slot_2,
1955  winstate->frametail_slot))
1956  winstate->frametailgroup++;
1957  }
1958  ExecClearTuple(winstate->temp_slot_2);
1959  winstate->frametail_valid = true;
1960  }
1961  else
1962  Assert(false);
1963  }
1964  else
1965  Assert(false);
1966 
1967  MemoryContextSwitchTo(oldcontext);
1968 }
1969 
1970 /*
1971  * update_grouptailpos
1972  * make grouptailpos valid for the current row
1973  *
1974  * May clobber winstate->temp_slot_2.
1975  */
1976 static void
1978 {
1979  WindowAgg *node = (WindowAgg *) winstate->ss.ps.plan;
1980  MemoryContext oldcontext;
1981 
1982  if (winstate->grouptail_valid)
1983  return; /* already known for current row */
1984 
1985  /* We may be called in a short-lived context */
1987 
1988  /* If no ORDER BY, all rows are peers with each other */
1989  if (node->ordNumCols == 0)
1990  {
1991  spool_tuples(winstate, -1);
1992  winstate->grouptailpos = winstate->spooled_rows;
1993  winstate->grouptail_valid = true;
1994  MemoryContextSwitchTo(oldcontext);
1995  return;
1996  }
1997 
1998  /*
1999  * Because grouptail_valid is reset only when current row advances into a
2000  * new peer group, we always reach here knowing that grouptailpos needs to
2001  * be advanced by at least one row. Hence, unlike the otherwise similar
2002  * case for frame tail tracking, we do not need persistent storage of the
2003  * group tail row.
2004  */
2005  Assert(winstate->grouptailpos <= winstate->currentpos);
2007  winstate->grouptail_ptr);
2008  for (;;)
2009  {
2010  /* Note we advance grouptailpos even if the fetch fails */
2011  winstate->grouptailpos++;
2012  spool_tuples(winstate, winstate->grouptailpos);
2013  if (!tuplestore_gettupleslot(winstate->buffer, true, true,
2014  winstate->temp_slot_2))
2015  break; /* end of partition */
2016  if (winstate->grouptailpos > winstate->currentpos &&
2017  !are_peers(winstate, winstate->temp_slot_2,
2018  winstate->ss.ss_ScanTupleSlot))
2019  break; /* this row is the group tail */
2020  }
2021  ExecClearTuple(winstate->temp_slot_2);
2022  winstate->grouptail_valid = true;
2023 
2024  MemoryContextSwitchTo(oldcontext);
2025 }
2026 
2027 
2028 /* -----------------
2029  * ExecWindowAgg
2030  *
2031  * ExecWindowAgg receives tuples from its outer subplan and
2032  * stores them into a tuplestore, then processes window functions.
2033  * This node doesn't reduce nor qualify any row so the number of
2034  * returned rows is exactly the same as its outer subplan's result.
2035  * -----------------
2036  */
2037 static TupleTableSlot *
2039 {
2040  WindowAggState *winstate = castNode(WindowAggState, pstate);
2041  TupleTableSlot *slot;
2042  ExprContext *econtext;
2043  int i;
2044  int numfuncs;
2045 
2047 
2048  if (winstate->status == WINDOWAGG_DONE)
2049  return NULL;
2050 
2051  /*
2052  * Compute frame offset values, if any, during first call (or after a
2053  * rescan). These are assumed to hold constant throughout the scan; if
2054  * user gives us a volatile expression, we'll only use its initial value.
2055  */
2056  if (winstate->all_first)
2057  {
2058  int frameOptions = winstate->frameOptions;
2059  Datum value;
2060  bool isnull;
2061  int16 len;
2062  bool byval;
2063 
2064  econtext = winstate->ss.ps.ps_ExprContext;
2065 
2066  if (frameOptions & FRAMEOPTION_START_OFFSET)
2067  {
2068  Assert(winstate->startOffset != NULL);
2070  econtext,
2071  &isnull);
2072  if (isnull)
2073  ereport(ERROR,
2074  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2075  errmsg("frame starting offset must not be null")));
2076  /* copy value into query-lifespan context */
2077  get_typlenbyval(exprType((Node *) winstate->startOffset->expr),
2078  &len, &byval);
2079  winstate->startOffsetValue = datumCopy(value, byval, len);
2080  if (frameOptions & (FRAMEOPTION_ROWS | FRAMEOPTION_GROUPS))
2081  {
2082  /* value is known to be int8 */
2083  int64 offset = DatumGetInt64(value);
2084 
2085  if (offset < 0)
2086  ereport(ERROR,
2087  (errcode(ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE),
2088  errmsg("frame starting offset must not be negative")));
2089  }
2090  }
2091  if (frameOptions & FRAMEOPTION_END_OFFSET)
2092  {
2093  Assert(winstate->endOffset != NULL);
2095  econtext,
2096  &isnull);
2097  if (isnull)
2098  ereport(ERROR,
2099  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2100  errmsg("frame ending offset must not be null")));
2101  /* copy value into query-lifespan context */
2102  get_typlenbyval(exprType((Node *) winstate->endOffset->expr),
2103  &len, &byval);
2104  winstate->endOffsetValue = datumCopy(value, byval, len);
2105  if (frameOptions & (FRAMEOPTION_ROWS | FRAMEOPTION_GROUPS))
2106  {
2107  /* value is known to be int8 */
2108  int64 offset = DatumGetInt64(value);
2109 
2110  if (offset < 0)
2111  ereport(ERROR,
2112  (errcode(ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE),
2113  errmsg("frame ending offset must not be negative")));
2114  }
2115  }
2116  winstate->all_first = false;
2117  }
2118 
2119  /* We need to loop as the runCondition or qual may filter out tuples */
2120  for (;;)
2121  {
2122  if (winstate->buffer == NULL)
2123  {
2124  /* Initialize for first partition and set current row = 0 */
2125  begin_partition(winstate);
2126  /* If there are no input rows, we'll detect that and exit below */
2127  }
2128  else
2129  {
2130  /* Advance current row within partition */
2131  winstate->currentpos++;
2132  /* This might mean that the frame moves, too */
2133  winstate->framehead_valid = false;
2134  winstate->frametail_valid = false;
2135  /* we don't need to invalidate grouptail here; see below */
2136  }
2137 
2138  /*
2139  * Spool all tuples up to and including the current row, if we haven't
2140  * already
2141  */
2142  spool_tuples(winstate, winstate->currentpos);
2143 
2144  /* Move to the next partition if we reached the end of this partition */
2145  if (winstate->partition_spooled &&
2146  winstate->currentpos >= winstate->spooled_rows)
2147  {
2148  release_partition(winstate);
2149 
2150  if (winstate->more_partitions)
2151  {
2152  begin_partition(winstate);
2153  Assert(winstate->spooled_rows > 0);
2154 
2155  /* Come out of pass-through mode when changing partition */
2156  winstate->status = WINDOWAGG_RUN;
2157  }
2158  else
2159  {
2160  /* No further partitions? We're done */
2161  winstate->status = WINDOWAGG_DONE;
2162  return NULL;
2163  }
2164  }
2165 
2166  /* final output execution is in ps_ExprContext */
2167  econtext = winstate->ss.ps.ps_ExprContext;
2168 
2169  /* Clear the per-output-tuple context for current row */
2170  ResetExprContext(econtext);
2171 
2172  /*
2173  * Read the current row from the tuplestore, and save in
2174  * ScanTupleSlot. (We can't rely on the outerplan's output slot
2175  * because we may have to read beyond the current row. Also, we have
2176  * to actually copy the row out of the tuplestore, since window
2177  * function evaluation might cause the tuplestore to dump its state to
2178  * disk.)
2179  *
2180  * In GROUPS mode, or when tracking a group-oriented exclusion clause,
2181  * we must also detect entering a new peer group and update associated
2182  * state when that happens. We use temp_slot_2 to temporarily hold
2183  * the previous row for this purpose.
2184  *
2185  * Current row must be in the tuplestore, since we spooled it above.
2186  */
2187  tuplestore_select_read_pointer(winstate->buffer, winstate->current_ptr);
2188  if ((winstate->frameOptions & (FRAMEOPTION_GROUPS |
2191  winstate->currentpos > 0)
2192  {
2193  ExecCopySlot(winstate->temp_slot_2, winstate->ss.ss_ScanTupleSlot);
2194  if (!tuplestore_gettupleslot(winstate->buffer, true, true,
2195  winstate->ss.ss_ScanTupleSlot))
2196  elog(ERROR, "unexpected end of tuplestore");
2197  if (!are_peers(winstate, winstate->temp_slot_2,
2198  winstate->ss.ss_ScanTupleSlot))
2199  {
2200  winstate->currentgroup++;
2201  winstate->groupheadpos = winstate->currentpos;
2202  winstate->grouptail_valid = false;
2203  }
2204  ExecClearTuple(winstate->temp_slot_2);
2205  }
2206  else
2207  {
2208  if (!tuplestore_gettupleslot(winstate->buffer, true, true,
2209  winstate->ss.ss_ScanTupleSlot))
2210  elog(ERROR, "unexpected end of tuplestore");
2211  }
2212 
2213  /* don't evaluate the window functions when we're in pass-through mode */
2214  if (winstate->status == WINDOWAGG_RUN)
2215  {
2216  /*
2217  * Evaluate true window functions
2218  */
2219  numfuncs = winstate->numfuncs;
2220  for (i = 0; i < numfuncs; i++)
2221  {
2222  WindowStatePerFunc perfuncstate = &(winstate->perfunc[i]);
2223 
2224  if (perfuncstate->plain_agg)
2225  continue;
2226  eval_windowfunction(winstate, perfuncstate,
2227  &(econtext->ecxt_aggvalues[perfuncstate->wfuncstate->wfuncno]),
2228  &(econtext->ecxt_aggnulls[perfuncstate->wfuncstate->wfuncno]));
2229  }
2230 
2231  /*
2232  * Evaluate aggregates
2233  */
2234  if (winstate->numaggs > 0)
2235  eval_windowaggregates(winstate);
2236  }
2237 
2238  /*
2239  * If we have created auxiliary read pointers for the frame or group
2240  * boundaries, force them to be kept up-to-date, because we don't know
2241  * whether the window function(s) will do anything that requires that.
2242  * Failing to advance the pointers would result in being unable to
2243  * trim data from the tuplestore, which is bad. (If we could know in
2244  * advance whether the window functions will use frame boundary info,
2245  * we could skip creating these pointers in the first place ... but
2246  * unfortunately the window function API doesn't require that.)
2247  */
2248  if (winstate->framehead_ptr >= 0)
2249  update_frameheadpos(winstate);
2250  if (winstate->frametail_ptr >= 0)
2251  update_frametailpos(winstate);
2252  if (winstate->grouptail_ptr >= 0)
2253  update_grouptailpos(winstate);
2254 
2255  /*
2256  * Truncate any no-longer-needed rows from the tuplestore.
2257  */
2258  tuplestore_trim(winstate->buffer);
2259 
2260  /*
2261  * Form and return a projection tuple using the windowfunc results and
2262  * the current row. Setting ecxt_outertuple arranges that any Vars
2263  * will be evaluated with respect to that row.
2264  */
2265  econtext->ecxt_outertuple = winstate->ss.ss_ScanTupleSlot;
2266 
2267  slot = ExecProject(winstate->ss.ps.ps_ProjInfo);
2268 
2269  if (winstate->status == WINDOWAGG_RUN)
2270  {
2271  econtext->ecxt_scantuple = slot;
2272 
2273  /*
2274  * Now evaluate the run condition to see if we need to go into
2275  * pass-through mode, or maybe stop completely.
2276  */
2277  if (!ExecQual(winstate->runcondition, econtext))
2278  {
2279  /*
2280  * Determine which mode to move into. If there is no
2281  * PARTITION BY clause and we're the top-level WindowAgg then
2282  * we're done. This tuple and any future tuples cannot
2283  * possibly match the runcondition. However, when there is a
2284  * PARTITION BY clause or we're not the top-level window we
2285  * can't just stop as we need to either process other
2286  * partitions or ensure WindowAgg nodes above us receive all
2287  * of the tuples they need to process their WindowFuncs.
2288  */
2289  if (winstate->use_pass_through)
2290  {
2291  /*
2292  * STRICT pass-through mode is required for the top window
2293  * when there is a PARTITION BY clause. Otherwise we must
2294  * ensure we store tuples that don't match the
2295  * runcondition so they're available to WindowAggs above.
2296  */
2297  if (winstate->top_window)
2298  {
2300  continue;
2301  }
2302  else
2303  winstate->status = WINDOWAGG_PASSTHROUGH;
2304  }
2305  else
2306  {
2307  /*
2308  * Pass-through not required. We can just return NULL.
2309  * Nothing else will match the runcondition.
2310  */
2311  winstate->status = WINDOWAGG_DONE;
2312  return NULL;
2313  }
2314  }
2315 
2316  /*
2317  * Filter out any tuples we don't need in the top-level WindowAgg.
2318  */
2319  if (!ExecQual(winstate->ss.ps.qual, econtext))
2320  {
2321  InstrCountFiltered1(winstate, 1);
2322  continue;
2323  }
2324 
2325  break;
2326  }
2327 
2328  /*
2329  * When not in WINDOWAGG_RUN mode, we must still return this tuple if
2330  * we're anything apart from the top window.
2331  */
2332  else if (!winstate->top_window)
2333  break;
2334  }
2335 
2336  return slot;
2337 }
2338 
2339 /* -----------------
2340  * ExecInitWindowAgg
2341  *
2342  * Creates the run-time information for the WindowAgg node produced by the
2343  * planner and initializes its outer subtree
2344  * -----------------
2345  */
2347 ExecInitWindowAgg(WindowAgg *node, EState *estate, int eflags)
2348 {
2349  WindowAggState *winstate;
2350  Plan *outerPlan;
2351  ExprContext *econtext;
2352  ExprContext *tmpcontext;
2353  WindowStatePerFunc perfunc;
2354  WindowStatePerAgg peragg;
2355  int frameOptions = node->frameOptions;
2356  int numfuncs,
2357  wfuncno,
2358  numaggs,
2359  aggno;
2360  TupleDesc scanDesc;
2361  ListCell *l;
2362 
2363  /* check for unsupported flags */
2364  Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
2365 
2366  /*
2367  * create state structure
2368  */
2369  winstate = makeNode(WindowAggState);
2370  winstate->ss.ps.plan = (Plan *) node;
2371  winstate->ss.ps.state = estate;
2372  winstate->ss.ps.ExecProcNode = ExecWindowAgg;
2373 
2374  /*
2375  * Create expression contexts. We need two, one for per-input-tuple
2376  * processing and one for per-output-tuple processing. We cheat a little
2377  * by using ExecAssignExprContext() to build both.
2378  */
2379  ExecAssignExprContext(estate, &winstate->ss.ps);
2380  tmpcontext = winstate->ss.ps.ps_ExprContext;
2381  winstate->tmpcontext = tmpcontext;
2382  ExecAssignExprContext(estate, &winstate->ss.ps);
2383 
2384  /* Create long-lived context for storage of partition-local memory etc */
2385  winstate->partcontext =
2387  "WindowAgg Partition",
2389 
2390  /*
2391  * Create mid-lived context for aggregate trans values etc.
2392  *
2393  * Note that moving aggregates each use their own private context, not
2394  * this one.
2395  */
2396  winstate->aggcontext =
2398  "WindowAgg Aggregates",
2400 
2401  /* Only the top-level WindowAgg may have a qual */
2402  Assert(node->plan.qual == NIL || node->topWindow);
2403 
2404  /* Initialize the qual */
2405  winstate->ss.ps.qual = ExecInitQual(node->plan.qual,
2406  (PlanState *) winstate);
2407 
2408  /*
2409  * Setup the run condition, if we received one from the query planner.
2410  * When set, this may allow us to move into pass-through mode so that we
2411  * don't have to perform any further evaluation of WindowFuncs in the
2412  * current partition or possibly stop returning tuples altogether when all
2413  * tuples are in the same partition.
2414  */
2415  winstate->runcondition = ExecInitQual(node->runCondition,
2416  (PlanState *) winstate);
2417 
2418  /*
2419  * When we're not the top-level WindowAgg node or we are but have a
2420  * PARTITION BY clause we must move into one of the WINDOWAGG_PASSTHROUGH*
2421  * modes when the runCondition becomes false.
2422  */
2423  winstate->use_pass_through = !node->topWindow || node->partNumCols > 0;
2424 
2425  /* remember if we're the top-window or we are below the top-window */
2426  winstate->top_window = node->topWindow;
2427 
2428  /*
2429  * initialize child nodes
2430  */
2431  outerPlan = outerPlan(node);
2432  outerPlanState(winstate) = ExecInitNode(outerPlan, estate, eflags);
2433 
2434  /*
2435  * initialize source tuple type (which is also the tuple type that we'll
2436  * store in the tuplestore and use in all our working slots).
2437  */
2439  scanDesc = winstate->ss.ss_ScanTupleSlot->tts_tupleDescriptor;
2440 
2441  /* the outer tuple isn't the child's tuple, but always a minimal tuple */
2442  winstate->ss.ps.outeropsset = true;
2443  winstate->ss.ps.outerops = &TTSOpsMinimalTuple;
2444  winstate->ss.ps.outeropsfixed = true;
2445 
2446  /*
2447  * tuple table initialization
2448  */
2449  winstate->first_part_slot = ExecInitExtraTupleSlot(estate, scanDesc,
2451  winstate->agg_row_slot = ExecInitExtraTupleSlot(estate, scanDesc,
2453  winstate->temp_slot_1 = ExecInitExtraTupleSlot(estate, scanDesc,
2455  winstate->temp_slot_2 = ExecInitExtraTupleSlot(estate, scanDesc,
2457 
2458  /*
2459  * create frame head and tail slots only if needed (must create slots in
2460  * exactly the same cases that update_frameheadpos and update_frametailpos
2461  * need them)
2462  */
2463  winstate->framehead_slot = winstate->frametail_slot = NULL;
2464 
2465  if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
2466  {
2467  if (((frameOptions & FRAMEOPTION_START_CURRENT_ROW) &&
2468  node->ordNumCols != 0) ||
2469  (frameOptions & FRAMEOPTION_START_OFFSET))
2470  winstate->framehead_slot = ExecInitExtraTupleSlot(estate, scanDesc,
2472  if (((frameOptions & FRAMEOPTION_END_CURRENT_ROW) &&
2473  node->ordNumCols != 0) ||
2474  (frameOptions & FRAMEOPTION_END_OFFSET))
2475  winstate->frametail_slot = ExecInitExtraTupleSlot(estate, scanDesc,
2477  }
2478 
2479  /*
2480  * Initialize result slot, type and projection.
2481  */
2483  ExecAssignProjectionInfo(&winstate->ss.ps, NULL);
2484 
2485  /* Set up data for comparing tuples */
2486  if (node->partNumCols > 0)
2487  winstate->partEqfunction =
2488  execTuplesMatchPrepare(scanDesc,
2489  node->partNumCols,
2490  node->partColIdx,
2491  node->partOperators,
2492  node->partCollations,
2493  &winstate->ss.ps);
2494 
2495  if (node->ordNumCols > 0)
2496  winstate->ordEqfunction =
2497  execTuplesMatchPrepare(scanDesc,
2498  node->ordNumCols,
2499  node->ordColIdx,
2500  node->ordOperators,
2501  node->ordCollations,
2502  &winstate->ss.ps);
2503 
2504  /*
2505  * WindowAgg nodes use aggvalues and aggnulls as well as Agg nodes.
2506  */
2507  numfuncs = winstate->numfuncs;
2508  numaggs = winstate->numaggs;
2509  econtext = winstate->ss.ps.ps_ExprContext;
2510  econtext->ecxt_aggvalues = (Datum *) palloc0(sizeof(Datum) * numfuncs);
2511  econtext->ecxt_aggnulls = (bool *) palloc0(sizeof(bool) * numfuncs);
2512 
2513  /*
2514  * allocate per-wfunc/per-agg state information.
2515  */
2516  perfunc = (WindowStatePerFunc) palloc0(sizeof(WindowStatePerFuncData) * numfuncs);
2517  peragg = (WindowStatePerAgg) palloc0(sizeof(WindowStatePerAggData) * numaggs);
2518  winstate->perfunc = perfunc;
2519  winstate->peragg = peragg;
2520 
2521  wfuncno = -1;
2522  aggno = -1;
2523  foreach(l, winstate->funcs)
2524  {
2525  WindowFuncExprState *wfuncstate = (WindowFuncExprState *) lfirst(l);
2526  WindowFunc *wfunc = wfuncstate->wfunc;
2527  WindowStatePerFunc perfuncstate;
2528  AclResult aclresult;
2529  int i;
2530 
2531  if (wfunc->winref != node->winref) /* planner screwed up? */
2532  elog(ERROR, "WindowFunc with winref %u assigned to WindowAgg with winref %u",
2533  wfunc->winref, node->winref);
2534 
2535  /* Look for a previous duplicate window function */
2536  for (i = 0; i <= wfuncno; i++)
2537  {
2538  if (equal(wfunc, perfunc[i].wfunc) &&
2539  !contain_volatile_functions((Node *) wfunc))
2540  break;
2541  }
2542  if (i <= wfuncno)
2543  {
2544  /* Found a match to an existing entry, so just mark it */
2545  wfuncstate->wfuncno = i;
2546  continue;
2547  }
2548 
2549  /* Nope, so assign a new PerAgg record */
2550  perfuncstate = &perfunc[++wfuncno];
2551 
2552  /* Mark WindowFunc state node with assigned index in the result array */
2553  wfuncstate->wfuncno = wfuncno;
2554 
2555  /* Check permission to call window function */
2556  aclresult = object_aclcheck(ProcedureRelationId, wfunc->winfnoid, GetUserId(),
2557  ACL_EXECUTE);
2558  if (aclresult != ACLCHECK_OK)
2559  aclcheck_error(aclresult, OBJECT_FUNCTION,
2560  get_func_name(wfunc->winfnoid));
2562 
2563  /* Fill in the perfuncstate data */
2564  perfuncstate->wfuncstate = wfuncstate;
2565  perfuncstate->wfunc = wfunc;
2566  perfuncstate->numArguments = list_length(wfuncstate->args);
2567  perfuncstate->winCollation = wfunc->inputcollid;
2568 
2569  get_typlenbyval(wfunc->wintype,
2570  &perfuncstate->resulttypeLen,
2571  &perfuncstate->resulttypeByVal);
2572 
2573  /*
2574  * If it's really just a plain aggregate function, we'll emulate the
2575  * Agg environment for it.
2576  */
2577  perfuncstate->plain_agg = wfunc->winagg;
2578  if (wfunc->winagg)
2579  {
2580  WindowStatePerAgg peraggstate;
2581 
2582  perfuncstate->aggno = ++aggno;
2583  peraggstate = &winstate->peragg[aggno];
2584  initialize_peragg(winstate, wfunc, peraggstate);
2585  peraggstate->wfuncno = wfuncno;
2586  }
2587  else
2588  {
2590 
2591  winobj->winstate = winstate;
2592  winobj->argstates = wfuncstate->args;
2593  winobj->localmem = NULL;
2594  perfuncstate->winobj = winobj;
2595 
2596  /* It's a real window function, so set up to call it. */
2597  fmgr_info_cxt(wfunc->winfnoid, &perfuncstate->flinfo,
2598  econtext->ecxt_per_query_memory);
2599  fmgr_info_set_expr((Node *) wfunc, &perfuncstate->flinfo);
2600  }
2601  }
2602 
2603  /* Update numfuncs, numaggs to match number of unique functions found */
2604  winstate->numfuncs = wfuncno + 1;
2605  winstate->numaggs = aggno + 1;
2606 
2607  /* Set up WindowObject for aggregates, if needed */
2608  if (winstate->numaggs > 0)
2609  {
2610  WindowObject agg_winobj = makeNode(WindowObjectData);
2611 
2612  agg_winobj->winstate = winstate;
2613  agg_winobj->argstates = NIL;
2614  agg_winobj->localmem = NULL;
2615  /* make sure markptr = -1 to invalidate. It may not get used */
2616  agg_winobj->markptr = -1;
2617  agg_winobj->readptr = -1;
2618  winstate->agg_winobj = agg_winobj;
2619  }
2620 
2621  /* Set the status to running */
2622  winstate->status = WINDOWAGG_RUN;
2623 
2624  /* copy frame options to state node for easy access */
2625  winstate->frameOptions = frameOptions;
2626 
2627  /* initialize frame bound offset expressions */
2628  winstate->startOffset = ExecInitExpr((Expr *) node->startOffset,
2629  (PlanState *) winstate);
2630  winstate->endOffset = ExecInitExpr((Expr *) node->endOffset,
2631  (PlanState *) winstate);
2632 
2633  /* Lookup in_range support functions if needed */
2634  if (OidIsValid(node->startInRangeFunc))
2635  fmgr_info(node->startInRangeFunc, &winstate->startInRangeFunc);
2636  if (OidIsValid(node->endInRangeFunc))
2637  fmgr_info(node->endInRangeFunc, &winstate->endInRangeFunc);
2638  winstate->inRangeColl = node->inRangeColl;
2639  winstate->inRangeAsc = node->inRangeAsc;
2640  winstate->inRangeNullsFirst = node->inRangeNullsFirst;
2641 
2642  winstate->all_first = true;
2643  winstate->partition_spooled = false;
2644  winstate->more_partitions = false;
2645 
2646  return winstate;
2647 }
2648 
2649 /* -----------------
2650  * ExecEndWindowAgg
2651  * -----------------
2652  */
2653 void
2655 {
2657  int i;
2658 
2659  release_partition(node);
2660 
2664  ExecClearTuple(node->temp_slot_1);
2665  ExecClearTuple(node->temp_slot_2);
2666  if (node->framehead_slot)
2668  if (node->frametail_slot)
2670 
2671  /*
2672  * Free both the expr contexts.
2673  */
2674  ExecFreeExprContext(&node->ss.ps);
2675  node->ss.ps.ps_ExprContext = node->tmpcontext;
2676  ExecFreeExprContext(&node->ss.ps);
2677 
2678  for (i = 0; i < node->numaggs; i++)
2679  {
2680  if (node->peragg[i].aggcontext != node->aggcontext)
2682  }
2685 
2686  pfree(node->perfunc);
2687  pfree(node->peragg);
2688 
2689  outerPlan = outerPlanState(node);
2691 }
2692 
2693 /* -----------------
2694  * ExecReScanWindowAgg
2695  * -----------------
2696  */
2697 void
2699 {
2701  ExprContext *econtext = node->ss.ps.ps_ExprContext;
2702 
2703  node->status = WINDOWAGG_RUN;
2704  node->all_first = true;
2705 
2706  /* release tuplestore et al */
2707  release_partition(node);
2708 
2709  /* release all temp tuples, but especially first_part_slot */
2713  ExecClearTuple(node->temp_slot_1);
2714  ExecClearTuple(node->temp_slot_2);
2715  if (node->framehead_slot)
2717  if (node->frametail_slot)
2719 
2720  /* Forget current wfunc values */
2721  MemSet(econtext->ecxt_aggvalues, 0, sizeof(Datum) * node->numfuncs);
2722  MemSet(econtext->ecxt_aggnulls, 0, sizeof(bool) * node->numfuncs);
2723 
2724  /*
2725  * if chgParam of subnode is not null then plan will be re-scanned by
2726  * first ExecProcNode.
2727  */
2728  if (outerPlan->chgParam == NULL)
2730 }
2731 
2732 /*
2733  * initialize_peragg
2734  *
2735  * Almost same as in nodeAgg.c, except we don't support DISTINCT currently.
2736  */
2737 static WindowStatePerAggData *
2739  WindowStatePerAgg peraggstate)
2740 {
2741  Oid inputTypes[FUNC_MAX_ARGS];
2742  int numArguments;
2743  HeapTuple aggTuple;
2744  Form_pg_aggregate aggform;
2745  Oid aggtranstype;
2746  AttrNumber initvalAttNo;
2747  AclResult aclresult;
2748  bool use_ma_code;
2749  Oid transfn_oid,
2750  invtransfn_oid,
2751  finalfn_oid;
2752  bool finalextra;
2753  char finalmodify;
2754  Expr *transfnexpr,
2755  *invtransfnexpr,
2756  *finalfnexpr;
2757  Datum textInitVal;
2758  int i;
2759  ListCell *lc;
2760 
2761  numArguments = list_length(wfunc->args);
2762 
2763  i = 0;
2764  foreach(lc, wfunc->args)
2765  {
2766  inputTypes[i++] = exprType((Node *) lfirst(lc));
2767  }
2768 
2769  aggTuple = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(wfunc->winfnoid));
2770  if (!HeapTupleIsValid(aggTuple))
2771  elog(ERROR, "cache lookup failed for aggregate %u",
2772  wfunc->winfnoid);
2773  aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
2774 
2775  /*
2776  * Figure out whether we want to use the moving-aggregate implementation,
2777  * and collect the right set of fields from the pg_attribute entry.
2778  *
2779  * It's possible that an aggregate would supply a safe moving-aggregate
2780  * implementation and an unsafe normal one, in which case our hand is
2781  * forced. Otherwise, if the frame head can't move, we don't need
2782  * moving-aggregate code. Even if we'd like to use it, don't do so if the
2783  * aggregate's arguments (and FILTER clause if any) contain any calls to
2784  * volatile functions. Otherwise, the difference between restarting and
2785  * not restarting the aggregation would be user-visible.
2786  */
2787  if (!OidIsValid(aggform->aggminvtransfn))
2788  use_ma_code = false; /* sine qua non */
2789  else if (aggform->aggmfinalmodify == AGGMODIFY_READ_ONLY &&
2790  aggform->aggfinalmodify != AGGMODIFY_READ_ONLY)
2791  use_ma_code = true; /* decision forced by safety */
2793  use_ma_code = false; /* non-moving frame head */
2794  else if (contain_volatile_functions((Node *) wfunc))
2795  use_ma_code = false; /* avoid possible behavioral change */
2796  else
2797  use_ma_code = true; /* yes, let's use it */
2798  if (use_ma_code)
2799  {
2800  peraggstate->transfn_oid = transfn_oid = aggform->aggmtransfn;
2801  peraggstate->invtransfn_oid = invtransfn_oid = aggform->aggminvtransfn;
2802  peraggstate->finalfn_oid = finalfn_oid = aggform->aggmfinalfn;
2803  finalextra = aggform->aggmfinalextra;
2804  finalmodify = aggform->aggmfinalmodify;
2805  aggtranstype = aggform->aggmtranstype;
2806  initvalAttNo = Anum_pg_aggregate_aggminitval;
2807  }
2808  else
2809  {
2810  peraggstate->transfn_oid = transfn_oid = aggform->aggtransfn;
2811  peraggstate->invtransfn_oid = invtransfn_oid = InvalidOid;
2812  peraggstate->finalfn_oid = finalfn_oid = aggform->aggfinalfn;
2813  finalextra = aggform->aggfinalextra;
2814  finalmodify = aggform->aggfinalmodify;
2815  aggtranstype = aggform->aggtranstype;
2816  initvalAttNo = Anum_pg_aggregate_agginitval;
2817  }
2818 
2819  /*
2820  * ExecInitWindowAgg already checked permission to call aggregate function
2821  * ... but we still need to check the component functions
2822  */
2823 
2824  /* Check that aggregate owner has permission to call component fns */
2825  {
2826  HeapTuple procTuple;
2827  Oid aggOwner;
2828 
2829  procTuple = SearchSysCache1(PROCOID,
2830  ObjectIdGetDatum(wfunc->winfnoid));
2831  if (!HeapTupleIsValid(procTuple))
2832  elog(ERROR, "cache lookup failed for function %u",
2833  wfunc->winfnoid);
2834  aggOwner = ((Form_pg_proc) GETSTRUCT(procTuple))->proowner;
2835  ReleaseSysCache(procTuple);
2836 
2837  aclresult = object_aclcheck(ProcedureRelationId, transfn_oid, aggOwner,
2838  ACL_EXECUTE);
2839  if (aclresult != ACLCHECK_OK)
2840  aclcheck_error(aclresult, OBJECT_FUNCTION,
2841  get_func_name(transfn_oid));
2842  InvokeFunctionExecuteHook(transfn_oid);
2843 
2844  if (OidIsValid(invtransfn_oid))
2845  {
2846  aclresult = object_aclcheck(ProcedureRelationId, invtransfn_oid, aggOwner,
2847  ACL_EXECUTE);
2848  if (aclresult != ACLCHECK_OK)
2849  aclcheck_error(aclresult, OBJECT_FUNCTION,
2850  get_func_name(invtransfn_oid));
2851  InvokeFunctionExecuteHook(invtransfn_oid);
2852  }
2853 
2854  if (OidIsValid(finalfn_oid))
2855  {
2856  aclresult = object_aclcheck(ProcedureRelationId, finalfn_oid, aggOwner,
2857  ACL_EXECUTE);
2858  if (aclresult != ACLCHECK_OK)
2859  aclcheck_error(aclresult, OBJECT_FUNCTION,
2860  get_func_name(finalfn_oid));
2861  InvokeFunctionExecuteHook(finalfn_oid);
2862  }
2863  }
2864 
2865  /*
2866  * If the selected finalfn isn't read-only, we can't run this aggregate as
2867  * a window function. This is a user-facing error, so we take a bit more
2868  * care with the error message than elsewhere in this function.
2869  */
2870  if (finalmodify != AGGMODIFY_READ_ONLY)
2871  ereport(ERROR,
2872  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2873  errmsg("aggregate function %s does not support use as a window function",
2874  format_procedure(wfunc->winfnoid))));
2875 
2876  /* Detect how many arguments to pass to the finalfn */
2877  if (finalextra)
2878  peraggstate->numFinalArgs = numArguments + 1;
2879  else
2880  peraggstate->numFinalArgs = 1;
2881 
2882  /* resolve actual type of transition state, if polymorphic */
2883  aggtranstype = resolve_aggregate_transtype(wfunc->winfnoid,
2884  aggtranstype,
2885  inputTypes,
2886  numArguments);
2887 
2888  /* build expression trees using actual argument & result types */
2889  build_aggregate_transfn_expr(inputTypes,
2890  numArguments,
2891  0, /* no ordered-set window functions yet */
2892  false, /* no variadic window functions yet */
2893  aggtranstype,
2894  wfunc->inputcollid,
2895  transfn_oid,
2896  invtransfn_oid,
2897  &transfnexpr,
2898  &invtransfnexpr);
2899 
2900  /* set up infrastructure for calling the transfn(s) and finalfn */
2901  fmgr_info(transfn_oid, &peraggstate->transfn);
2902  fmgr_info_set_expr((Node *) transfnexpr, &peraggstate->transfn);
2903 
2904  if (OidIsValid(invtransfn_oid))
2905  {
2906  fmgr_info(invtransfn_oid, &peraggstate->invtransfn);
2907  fmgr_info_set_expr((Node *) invtransfnexpr, &peraggstate->invtransfn);
2908  }
2909 
2910  if (OidIsValid(finalfn_oid))
2911  {
2912  build_aggregate_finalfn_expr(inputTypes,
2913  peraggstate->numFinalArgs,
2914  aggtranstype,
2915  wfunc->wintype,
2916  wfunc->inputcollid,
2917  finalfn_oid,
2918  &finalfnexpr);
2919  fmgr_info(finalfn_oid, &peraggstate->finalfn);
2920  fmgr_info_set_expr((Node *) finalfnexpr, &peraggstate->finalfn);
2921  }
2922 
2923  /* get info about relevant datatypes */
2924  get_typlenbyval(wfunc->wintype,
2925  &peraggstate->resulttypeLen,
2926  &peraggstate->resulttypeByVal);
2927  get_typlenbyval(aggtranstype,
2928  &peraggstate->transtypeLen,
2929  &peraggstate->transtypeByVal);
2930 
2931  /*
2932  * initval is potentially null, so don't try to access it as a struct
2933  * field. Must do it the hard way with SysCacheGetAttr.
2934  */
2935  textInitVal = SysCacheGetAttr(AGGFNOID, aggTuple, initvalAttNo,
2936  &peraggstate->initValueIsNull);
2937 
2938  if (peraggstate->initValueIsNull)
2939  peraggstate->initValue = (Datum) 0;
2940  else
2941  peraggstate->initValue = GetAggInitVal(textInitVal,
2942  aggtranstype);
2943 
2944  /*
2945  * If the transfn is strict and the initval is NULL, make sure input type
2946  * and transtype are the same (or at least binary-compatible), so that
2947  * it's OK to use the first input value as the initial transValue. This
2948  * should have been checked at agg definition time, but we must check
2949  * again in case the transfn's strictness property has been changed.
2950  */
2951  if (peraggstate->transfn.fn_strict && peraggstate->initValueIsNull)
2952  {
2953  if (numArguments < 1 ||
2954  !IsBinaryCoercible(inputTypes[0], aggtranstype))
2955  ereport(ERROR,
2956  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
2957  errmsg("aggregate %u needs to have compatible input type and transition type",
2958  wfunc->winfnoid)));
2959  }
2960 
2961  /*
2962  * Insist that forward and inverse transition functions have the same
2963  * strictness setting. Allowing them to differ would require handling
2964  * more special cases in advance_windowaggregate and
2965  * advance_windowaggregate_base, for no discernible benefit. This should
2966  * have been checked at agg definition time, but we must check again in
2967  * case either function's strictness property has been changed.
2968  */
2969  if (OidIsValid(invtransfn_oid) &&
2970  peraggstate->transfn.fn_strict != peraggstate->invtransfn.fn_strict)
2971  ereport(ERROR,
2972  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
2973  errmsg("strictness of aggregate's forward and inverse transition functions must match")));
2974 
2975  /*
2976  * Moving aggregates use their own aggcontext.
2977  *
2978  * This is necessary because they might restart at different times, so we
2979  * might never be able to reset the shared context otherwise. We can't
2980  * make it the aggregates' responsibility to clean up after themselves,
2981  * because strict aggregates must be restarted whenever we remove their
2982  * last non-NULL input, which the aggregate won't be aware is happening.
2983  * Also, just pfree()ing the transValue upon restarting wouldn't help,
2984  * since we'd miss any indirectly referenced data. We could, in theory,
2985  * make the memory allocation rules for moving aggregates different than
2986  * they have historically been for plain aggregates, but that seems grotty
2987  * and likely to lead to memory leaks.
2988  */
2989  if (OidIsValid(invtransfn_oid))
2990  peraggstate->aggcontext =
2992  "WindowAgg Per Aggregate",
2994  else
2995  peraggstate->aggcontext = winstate->aggcontext;
2996 
2997  ReleaseSysCache(aggTuple);
2998 
2999  return peraggstate;
3000 }
3001 
3002 static Datum
3003 GetAggInitVal(Datum textInitVal, Oid transtype)
3004 {
3005  Oid typinput,
3006  typioparam;
3007  char *strInitVal;
3008  Datum initVal;
3009 
3010  getTypeInputInfo(transtype, &typinput, &typioparam);
3011  strInitVal = TextDatumGetCString(textInitVal);
3012  initVal = OidInputFunctionCall(typinput, strInitVal,
3013  typioparam, -1);
3014  pfree(strInitVal);
3015  return initVal;
3016 }
3017 
3018 /*
3019  * are_peers
3020  * compare two rows to see if they are equal according to the ORDER BY clause
3021  *
3022  * NB: this does not consider the window frame mode.
3023  */
3024 static bool
3026  TupleTableSlot *slot2)
3027 {
3028  WindowAgg *node = (WindowAgg *) winstate->ss.ps.plan;
3029  ExprContext *econtext = winstate->tmpcontext;
3030 
3031  /* If no ORDER BY, all rows are peers with each other */
3032  if (node->ordNumCols == 0)
3033  return true;
3034 
3035  econtext->ecxt_outertuple = slot1;
3036  econtext->ecxt_innertuple = slot2;
3037  return ExecQualAndReset(winstate->ordEqfunction, econtext);
3038 }
3039 
3040 /*
3041  * window_gettupleslot
3042  * Fetch the pos'th tuple of the current partition into the slot,
3043  * using the winobj's read pointer
3044  *
3045  * Returns true if successful, false if no such row
3046  */
3047 static bool
3049 {
3050  WindowAggState *winstate = winobj->winstate;
3051  MemoryContext oldcontext;
3052 
3053  /* often called repeatedly in a row */
3055 
3056  /* Don't allow passing -1 to spool_tuples here */
3057  if (pos < 0)
3058  return false;
3059 
3060  /* If necessary, fetch the tuple into the spool */
3061  spool_tuples(winstate, pos);
3062 
3063  if (pos >= winstate->spooled_rows)
3064  return false;
3065 
3066  if (pos < winobj->markpos)
3067  elog(ERROR, "cannot fetch row before WindowObject's mark position");
3068 
3070 
3071  tuplestore_select_read_pointer(winstate->buffer, winobj->readptr);
3072 
3073  /*
3074  * Advance or rewind until we are within one tuple of the one we want.
3075  */
3076  if (winobj->seekpos < pos - 1)
3077  {
3078  if (!tuplestore_skiptuples(winstate->buffer,
3079  pos - 1 - winobj->seekpos,
3080  true))
3081  elog(ERROR, "unexpected end of tuplestore");
3082  winobj->seekpos = pos - 1;
3083  }
3084  else if (winobj->seekpos > pos + 1)
3085  {
3086  if (!tuplestore_skiptuples(winstate->buffer,
3087  winobj->seekpos - (pos + 1),
3088  false))
3089  elog(ERROR, "unexpected end of tuplestore");
3090  winobj->seekpos = pos + 1;
3091  }
3092  else if (winobj->seekpos == pos)
3093  {
3094  /*
3095  * There's no API to refetch the tuple at the current position. We
3096  * have to move one tuple forward, and then one backward. (We don't
3097  * do it the other way because we might try to fetch the row before
3098  * our mark, which isn't allowed.) XXX this case could stand to be
3099  * optimized.
3100  */
3101  tuplestore_advance(winstate->buffer, true);
3102  winobj->seekpos++;
3103  }
3104 
3105  /*
3106  * Now we should be on the tuple immediately before or after the one we
3107  * want, so just fetch forwards or backwards as appropriate.
3108  *
3109  * Notice that we tell tuplestore_gettupleslot to make a physical copy of
3110  * the fetched tuple. This ensures that the slot's contents remain valid
3111  * through manipulations of the tuplestore, which some callers depend on.
3112  */
3113  if (winobj->seekpos > pos)
3114  {
3115  if (!tuplestore_gettupleslot(winstate->buffer, false, true, slot))
3116  elog(ERROR, "unexpected end of tuplestore");
3117  winobj->seekpos--;
3118  }
3119  else
3120  {
3121  if (!tuplestore_gettupleslot(winstate->buffer, true, true, slot))
3122  elog(ERROR, "unexpected end of tuplestore");
3123  winobj->seekpos++;
3124  }
3125 
3126  Assert(winobj->seekpos == pos);
3127 
3128  MemoryContextSwitchTo(oldcontext);
3129 
3130  return true;
3131 }
3132 
3133 
3134 /***********************************************************************
3135  * API exposed to window functions
3136  ***********************************************************************/
3137 
3138 
3139 /*
3140  * WinGetPartitionLocalMemory
3141  * Get working memory that lives till end of partition processing
3142  *
3143  * On first call within a given partition, this allocates and zeroes the
3144  * requested amount of space. Subsequent calls just return the same chunk.
3145  *
3146  * Memory obtained this way is normally used to hold state that should be
3147  * automatically reset for each new partition. If a window function wants
3148  * to hold state across the whole query, fcinfo->fn_extra can be used in the
3149  * usual way for that.
3150  */
3151 void *
3153 {
3154  Assert(WindowObjectIsValid(winobj));
3155  if (winobj->localmem == NULL)
3156  winobj->localmem =
3158  return winobj->localmem;
3159 }
3160 
3161 /*
3162  * WinGetCurrentPosition
3163  * Return the current row's position (counting from 0) within the current
3164  * partition.
3165  */
3166 int64
3168 {
3169  Assert(WindowObjectIsValid(winobj));
3170  return winobj->winstate->currentpos;
3171 }
3172 
3173 /*
3174  * WinGetPartitionRowCount
3175  * Return total number of rows contained in the current partition.
3176  *
3177  * Note: this is a relatively expensive operation because it forces the
3178  * whole partition to be "spooled" into the tuplestore at once. Once
3179  * executed, however, additional calls within the same partition are cheap.
3180  */
3181 int64
3183 {
3184  Assert(WindowObjectIsValid(winobj));
3185  spool_tuples(winobj->winstate, -1);
3186  return winobj->winstate->spooled_rows;
3187 }
3188 
3189 /*
3190  * WinSetMarkPosition
3191  * Set the "mark" position for the window object, which is the oldest row
3192  * number (counting from 0) it is allowed to fetch during all subsequent
3193  * operations within the current partition.
3194  *
3195  * Window functions do not have to call this, but are encouraged to move the
3196  * mark forward when possible to keep the tuplestore size down and prevent
3197  * having to spill rows to disk.
3198  */
3199 void
3200 WinSetMarkPosition(WindowObject winobj, int64 markpos)
3201 {
3202  WindowAggState *winstate;
3203 
3204  Assert(WindowObjectIsValid(winobj));
3205  winstate = winobj->winstate;
3206 
3207  if (markpos < winobj->markpos)
3208  elog(ERROR, "cannot move WindowObject's mark position backward");
3209  tuplestore_select_read_pointer(winstate->buffer, winobj->markptr);
3210  if (markpos > winobj->markpos)
3211  {
3212  tuplestore_skiptuples(winstate->buffer,
3213  markpos - winobj->markpos,
3214  true);
3215  winobj->markpos = markpos;
3216  }
3217  tuplestore_select_read_pointer(winstate->buffer, winobj->readptr);
3218  if (markpos > winobj->seekpos)
3219  {
3220  tuplestore_skiptuples(winstate->buffer,
3221  markpos - winobj->seekpos,
3222  true);
3223  winobj->seekpos = markpos;
3224  }
3225 }
3226 
3227 /*
3228  * WinRowsArePeers
3229  * Compare two rows (specified by absolute position in partition) to see
3230  * if they are equal according to the ORDER BY clause.
3231  *
3232  * NB: this does not consider the window frame mode.
3233  */
3234 bool
3235 WinRowsArePeers(WindowObject winobj, int64 pos1, int64 pos2)
3236 {
3237  WindowAggState *winstate;
3238  WindowAgg *node;
3239  TupleTableSlot *slot1;
3240  TupleTableSlot *slot2;
3241  bool res;
3242 
3243  Assert(WindowObjectIsValid(winobj));
3244  winstate = winobj->winstate;
3245  node = (WindowAgg *) winstate->ss.ps.plan;
3246 
3247  /* If no ORDER BY, all rows are peers; don't bother to fetch them */
3248  if (node->ordNumCols == 0)
3249  return true;
3250 
3251  /*
3252  * Note: OK to use temp_slot_2 here because we aren't calling any
3253  * frame-related functions (those tend to clobber temp_slot_2).
3254  */
3255  slot1 = winstate->temp_slot_1;
3256  slot2 = winstate->temp_slot_2;
3257 
3258  if (!window_gettupleslot(winobj, pos1, slot1))
3259  elog(ERROR, "specified position is out of window: " INT64_FORMAT,
3260  pos1);
3261  if (!window_gettupleslot(winobj, pos2, slot2))
3262  elog(ERROR, "specified position is out of window: " INT64_FORMAT,
3263  pos2);
3264 
3265  res = are_peers(winstate, slot1, slot2);
3266 
3267  ExecClearTuple(slot1);
3268  ExecClearTuple(slot2);
3269 
3270  return res;
3271 }
3272 
3273 /*
3274  * WinGetFuncArgInPartition
3275  * Evaluate a window function's argument expression on a specified
3276  * row of the partition. The row is identified in lseek(2) style,
3277  * i.e. relative to the current, first, or last row.
3278  *
3279  * argno: argument number to evaluate (counted from 0)
3280  * relpos: signed rowcount offset from the seek position
3281  * seektype: WINDOW_SEEK_CURRENT, WINDOW_SEEK_HEAD, or WINDOW_SEEK_TAIL
3282  * set_mark: If the row is found and set_mark is true, the mark is moved to
3283  * the row as a side-effect.
3284  * isnull: output argument, receives isnull status of result
3285  * isout: output argument, set to indicate whether target row position
3286  * is out of partition (can pass NULL if caller doesn't care about this)
3287  *
3288  * Specifying a nonexistent row is not an error, it just causes a null result
3289  * (plus setting *isout true, if isout isn't NULL).
3290  */
3291 Datum
3293  int relpos, int seektype, bool set_mark,
3294  bool *isnull, bool *isout)
3295 {
3296  WindowAggState *winstate;
3297  ExprContext *econtext;
3298  TupleTableSlot *slot;
3299  bool gottuple;
3300  int64 abs_pos;
3301 
3302  Assert(WindowObjectIsValid(winobj));
3303  winstate = winobj->winstate;
3304  econtext = winstate->ss.ps.ps_ExprContext;
3305  slot = winstate->temp_slot_1;
3306 
3307  switch (seektype)
3308  {
3309  case WINDOW_SEEK_CURRENT:
3310  abs_pos = winstate->currentpos + relpos;
3311  break;
3312  case WINDOW_SEEK_HEAD:
3313  abs_pos = relpos;
3314  break;
3315  case WINDOW_SEEK_TAIL:
3316  spool_tuples(winstate, -1);
3317  abs_pos = winstate->spooled_rows - 1 + relpos;
3318  break;
3319  default:
3320  elog(ERROR, "unrecognized window seek type: %d", seektype);
3321  abs_pos = 0; /* keep compiler quiet */
3322  break;
3323  }
3324 
3325  gottuple = window_gettupleslot(winobj, abs_pos, slot);
3326 
3327  if (!gottuple)
3328  {
3329  if (isout)
3330  *isout = true;
3331  *isnull = true;
3332  return (Datum) 0;
3333  }
3334  else
3335  {
3336  if (isout)
3337  *isout = false;
3338  if (set_mark)
3339  WinSetMarkPosition(winobj, abs_pos);
3340  econtext->ecxt_outertuple = slot;
3341  return ExecEvalExpr((ExprState *) list_nth(winobj->argstates, argno),
3342  econtext, isnull);
3343  }
3344 }
3345 
3346 /*
3347  * WinGetFuncArgInFrame
3348  * Evaluate a window function's argument expression on a specified
3349  * row of the window frame. The row is identified in lseek(2) style,
3350  * i.e. relative to the first or last row of the frame. (We do not
3351  * support WINDOW_SEEK_CURRENT here, because it's not very clear what
3352  * that should mean if the current row isn't part of the frame.)
3353  *
3354  * argno: argument number to evaluate (counted from 0)
3355  * relpos: signed rowcount offset from the seek position
3356  * seektype: WINDOW_SEEK_HEAD or WINDOW_SEEK_TAIL
3357  * set_mark: If the row is found/in frame and set_mark is true, the mark is
3358  * moved to the row as a side-effect.
3359  * isnull: output argument, receives isnull status of result
3360  * isout: output argument, set to indicate whether target row position
3361  * is out of frame (can pass NULL if caller doesn't care about this)
3362  *
3363  * Specifying a nonexistent or not-in-frame row is not an error, it just
3364  * causes a null result (plus setting *isout true, if isout isn't NULL).
3365  *
3366  * Note that some exclusion-clause options lead to situations where the
3367  * rows that are in-frame are not consecutive in the partition. But we
3368  * count only in-frame rows when measuring relpos.
3369  *
3370  * The set_mark flag is interpreted as meaning that the caller will specify
3371  * a constant (or, perhaps, monotonically increasing) relpos in successive
3372  * calls, so that *if there is no exclusion clause* there will be no need
3373  * to fetch a row before the previously fetched row. But we do not expect
3374  * the caller to know how to account for exclusion clauses. Therefore,
3375  * if there is an exclusion clause we take responsibility for adjusting the
3376  * mark request to something that will be safe given the above assumption
3377  * about relpos.
3378  */
3379 Datum
3381  int relpos, int seektype, bool set_mark,
3382  bool *isnull, bool *isout)
3383 {
3384  WindowAggState *winstate;
3385  ExprContext *econtext;
3386  TupleTableSlot *slot;
3387  int64 abs_pos;
3388  int64 mark_pos;
3389 
3390  Assert(WindowObjectIsValid(winobj));
3391  winstate = winobj->winstate;
3392  econtext = winstate->ss.ps.ps_ExprContext;
3393  slot = winstate->temp_slot_1;
3394 
3395  switch (seektype)
3396  {
3397  case WINDOW_SEEK_CURRENT:
3398  elog(ERROR, "WINDOW_SEEK_CURRENT is not supported for WinGetFuncArgInFrame");
3399  abs_pos = mark_pos = 0; /* keep compiler quiet */
3400  break;
3401  case WINDOW_SEEK_HEAD:
3402  /* rejecting relpos < 0 is easy and simplifies code below */
3403  if (relpos < 0)
3404  goto out_of_frame;
3405  update_frameheadpos(winstate);
3406  abs_pos = winstate->frameheadpos + relpos;
3407  mark_pos = abs_pos;
3408 
3409  /*
3410  * Account for exclusion option if one is active, but advance only
3411  * abs_pos not mark_pos. This prevents changes of the current
3412  * row's peer group from resulting in trying to fetch a row before
3413  * some previous mark position.
3414  *
3415  * Note that in some corner cases such as current row being
3416  * outside frame, these calculations are theoretically too simple,
3417  * but it doesn't matter because we'll end up deciding the row is
3418  * out of frame. We do not attempt to avoid fetching rows past
3419  * end of frame; that would happen in some cases anyway.
3420  */
3421  switch (winstate->frameOptions & FRAMEOPTION_EXCLUSION)
3422  {
3423  case 0:
3424  /* no adjustment needed */
3425  break;
3427  if (abs_pos >= winstate->currentpos &&
3428  winstate->currentpos >= winstate->frameheadpos)
3429  abs_pos++;
3430  break;
3432  update_grouptailpos(winstate);
3433  if (abs_pos >= winstate->groupheadpos &&
3434  winstate->grouptailpos > winstate->frameheadpos)
3435  {
3436  int64 overlapstart = Max(winstate->groupheadpos,
3437  winstate->frameheadpos);
3438 
3439  abs_pos += winstate->grouptailpos - overlapstart;
3440  }
3441  break;
3443  update_grouptailpos(winstate);
3444  if (abs_pos >= winstate->groupheadpos &&
3445  winstate->grouptailpos > winstate->frameheadpos)
3446  {
3447  int64 overlapstart = Max(winstate->groupheadpos,
3448  winstate->frameheadpos);
3449 
3450  if (abs_pos == overlapstart)
3451  abs_pos = winstate->currentpos;
3452  else
3453  abs_pos += winstate->grouptailpos - overlapstart - 1;
3454  }
3455  break;
3456  default:
3457  elog(ERROR, "unrecognized frame option state: 0x%x",
3458  winstate->frameOptions);
3459  break;
3460  }
3461  break;
3462  case WINDOW_SEEK_TAIL:
3463  /* rejecting relpos > 0 is easy and simplifies code below */
3464  if (relpos > 0)
3465  goto out_of_frame;
3466  update_frametailpos(winstate);
3467  abs_pos = winstate->frametailpos - 1 + relpos;
3468 
3469  /*
3470  * Account for exclusion option if one is active. If there is no
3471  * exclusion, we can safely set the mark at the accessed row. But
3472  * if there is, we can only mark the frame start, because we can't
3473  * be sure how far back in the frame the exclusion might cause us
3474  * to fetch in future. Furthermore, we have to actually check
3475  * against frameheadpos here, since it's unsafe to try to fetch a
3476  * row before frame start if the mark might be there already.
3477  */
3478  switch (winstate->frameOptions & FRAMEOPTION_EXCLUSION)
3479  {
3480  case 0:
3481  /* no adjustment needed */
3482  mark_pos = abs_pos;
3483  break;
3485  if (abs_pos <= winstate->currentpos &&
3486  winstate->currentpos < winstate->frametailpos)
3487  abs_pos--;
3488  update_frameheadpos(winstate);
3489  if (abs_pos < winstate->frameheadpos)
3490  goto out_of_frame;
3491  mark_pos = winstate->frameheadpos;
3492  break;
3494  update_grouptailpos(winstate);
3495  if (abs_pos < winstate->grouptailpos &&
3496  winstate->groupheadpos < winstate->frametailpos)
3497  {
3498  int64 overlapend = Min(winstate->grouptailpos,
3499  winstate->frametailpos);
3500 
3501  abs_pos -= overlapend - winstate->groupheadpos;
3502  }
3503  update_frameheadpos(winstate);
3504  if (abs_pos < winstate->frameheadpos)
3505  goto out_of_frame;
3506  mark_pos = winstate->frameheadpos;
3507  break;
3509  update_grouptailpos(winstate);
3510  if (abs_pos < winstate->grouptailpos &&
3511  winstate->groupheadpos < winstate->frametailpos)
3512  {
3513  int64 overlapend = Min(winstate->grouptailpos,
3514  winstate->frametailpos);
3515 
3516  if (abs_pos == overlapend - 1)
3517  abs_pos = winstate->currentpos;
3518  else
3519  abs_pos -= overlapend - 1 - winstate->groupheadpos;
3520  }
3521  update_frameheadpos(winstate);
3522  if (abs_pos < winstate->frameheadpos)
3523  goto out_of_frame;
3524  mark_pos = winstate->frameheadpos;
3525  break;
3526  default:
3527  elog(ERROR, "unrecognized frame option state: 0x%x",
3528  winstate->frameOptions);
3529  mark_pos = 0; /* keep compiler quiet */
3530  break;
3531  }
3532  break;
3533  default:
3534  elog(ERROR, "unrecognized window seek type: %d", seektype);
3535  abs_pos = mark_pos = 0; /* keep compiler quiet */
3536  break;
3537  }
3538 
3539  if (!window_gettupleslot(winobj, abs_pos, slot))
3540  goto out_of_frame;
3541 
3542  /* The code above does not detect all out-of-frame cases, so check */
3543  if (row_is_in_frame(winstate, abs_pos, slot) <= 0)
3544  goto out_of_frame;
3545 
3546  if (isout)
3547  *isout = false;
3548  if (set_mark)
3549  WinSetMarkPosition(winobj, mark_pos);
3550  econtext->ecxt_outertuple = slot;
3551  return ExecEvalExpr((ExprState *) list_nth(winobj->argstates, argno),
3552  econtext, isnull);
3553 
3554 out_of_frame:
3555  if (isout)
3556  *isout = true;
3557  *isnull = true;
3558  return (Datum) 0;
3559 }
3560 
3561 /*
3562  * WinGetFuncArgCurrent
3563  * Evaluate a window function's argument expression on the current row.
3564  *
3565  * argno: argument number to evaluate (counted from 0)
3566  * isnull: output argument, receives isnull status of result
3567  *
3568  * Note: this isn't quite equivalent to WinGetFuncArgInPartition or
3569  * WinGetFuncArgInFrame targeting the current row, because it will succeed
3570  * even if the WindowObject's mark has been set beyond the current row.
3571  * This should generally be used for "ordinary" arguments of a window
3572  * function, such as the offset argument of lead() or lag().
3573  */
3574 Datum
3575 WinGetFuncArgCurrent(WindowObject winobj, int argno, bool *isnull)
3576 {
3577  WindowAggState *winstate;
3578  ExprContext *econtext;
3579 
3580  Assert(WindowObjectIsValid(winobj));
3581  winstate = winobj->winstate;
3582 
3583  econtext = winstate->ss.ps.ps_ExprContext;
3584 
3585  econtext->ecxt_outertuple = winstate->ss.ss_ScanTupleSlot;
3586  return ExecEvalExpr((ExprState *) list_nth(winobj->argstates, argno),
3587  econtext, isnull);
3588 }
AclResult
Definition: acl.h:183
@ ACLCHECK_OK
Definition: acl.h:184
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3485
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:4598
int16 AttrNumber
Definition: attnum.h:21
#define TextDatumGetCString(d)
Definition: builtins.h:86
#define Min(x, y)
Definition: c.h:937
signed short int16
Definition: c.h:429
#define Max(x, y)
Definition: c.h:931
#define INT64_FORMAT
Definition: c.h:484
#define MemSet(start, val, len)
Definition: c.h:953
#define OidIsValid(objectId)
Definition: c.h:711
size_t Size
Definition: c.h:541
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:448
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:225
void ExecReScan(PlanState *node)
Definition: execAmi.c:78
ExprState * ExecInitQual(List *qual, PlanState *parent)
Definition: execExpr.c:210
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:124
ExprState * execTuplesMatchPrepare(TupleDesc desc, int numCols, const AttrNumber *keyColIdx, const Oid *eqOperators, const Oid *collations, PlanState *parent)
Definition: execGrouping.c:59
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:557
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:142
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1831
void ExecInitResultTupleSlotTL(PlanState *planstate, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1799
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85
void ExecCreateScanSlotFromOuterPlan(EState *estate, ScanState *scanstate, const TupleTableSlotOps *tts_ops)
Definition: execUtils.c:684
void ExecAssignExprContext(EState *estate, PlanState *planstate)
Definition: execUtils.c:482
void ExecAssignProjectionInfo(PlanState *planstate, TupleDesc inputDesc)
Definition: execUtils.c:537
void ExecFreeExprContext(PlanState *planstate)
Definition: execUtils.c:652
struct WindowStatePerAggData * WindowStatePerAgg
Definition: execnodes.h:2439
#define InstrCountFiltered1(node, delta)
Definition: execnodes.h:1133
#define outerPlanState(node)
Definition: execnodes.h:1125
@ WINDOWAGG_PASSTHROUGH
Definition: execnodes.h:2448
@ WINDOWAGG_RUN
Definition: execnodes.h:2447
@ WINDOWAGG_DONE
Definition: execnodes.h:2446
@ WINDOWAGG_PASSTHROUGH_STRICT
Definition: execnodes.h:2449
struct WindowStatePerFuncData * WindowStatePerFunc
Definition: execnodes.h:2438
#define EXEC_FLAG_BACKWARD
Definition: executor.h:58
static TupleTableSlot * ExecProject(ProjectionInfo *projInfo)
Definition: executor.h:361
#define ResetExprContext(econtext)
Definition: executor.h:529
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:398
static bool ExecQualAndReset(ExprState *state, ExprContext *econtext)
Definition: executor.h:425
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:318
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:333
#define EXEC_FLAG_MARK
Definition: executor.h:59
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:254
ExpandedObjectHeader * DatumGetEOHP(Datum d)
Definition: expandeddatum.c:29
void DeleteExpandedObject(Datum d)
#define MakeExpandedObjectReadOnly(d, isnull, typlen)
#define DatumIsReadWriteExpandedObject(d, isnull, typlen)
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1630
Datum FunctionCall5Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2, Datum arg3, Datum arg4, Datum arg5)
Definition: fmgr.c:1208
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:136
#define InitFunctionCallInfoData(Fcinfo, Flinfo, Nargs, Collation, Context, Resultinfo)
Definition: fmgr.h:150
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
#define FunctionCallInvoke(fcinfo)
Definition: fmgr.h:172
#define fmgr_info_set_expr(expr, finfo)
Definition: fmgr.h:135
int work_mem
Definition: globals.c:125
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
static struct @143 value
int i
Definition: isn.c:73
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
Assert(fmt[strlen(fmt) - 1] !='\n')
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2209
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2832
char * get_func_name(Oid funcid)
Definition: lsyscache.c:1590
void pfree(void *pointer)
Definition: mcxt.c:1306
void * palloc0(Size size)
Definition: mcxt.c:1230
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:1037
MemoryContext CurrentMemoryContext
Definition: mcxt.c:124
MemoryContext MemoryContextGetParent(MemoryContext context)
Definition: mcxt.c:613
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:376
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:70
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
Oid GetUserId(void)
Definition: miscinit.c:497
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
Datum WinGetFuncArgInPartition(WindowObject winobj, int argno, int relpos, int seektype, bool set_mark, bool *isnull, bool *isout)
static void begin_partition(WindowAggState *winstate)
struct WindowObjectData WindowObjectData
static void update_grouptailpos(WindowAggState *winstate)
Datum WinGetFuncArgInFrame(WindowObject winobj, int argno, int relpos, int seektype, bool set_mark, bool *isnull, bool *isout)
WindowAggState * ExecInitWindowAgg(WindowAgg *node, EState *estate, int eflags)
struct WindowStatePerAggData WindowStatePerAggData
static Datum GetAggInitVal(Datum textInitVal, Oid transtype)
static void spool_tuples(WindowAggState *winstate, int64 pos)
static void advance_windowaggregate(WindowAggState *winstate, WindowStatePerFunc perfuncstate, WindowStatePerAgg peraggstate)
static int row_is_in_frame(WindowAggState *winstate, int64 pos, TupleTableSlot *slot)
void ExecEndWindowAgg(WindowAggState *node)
static void eval_windowfunction(WindowAggState *winstate, WindowStatePerFunc perfuncstate, Datum *result, bool *isnull)
struct WindowStatePerFuncData WindowStatePerFuncData
static WindowStatePerAggData * initialize_peragg(WindowAggState *winstate, WindowFunc *wfunc, WindowStatePerAgg peraggstate)
static void finalize_windowaggregate(WindowAggState *winstate, WindowStatePerFunc perfuncstate, WindowStatePerAgg peraggstate, Datum *result, bool *isnull)
static bool advance_windowaggregate_base(WindowAggState *winstate, WindowStatePerFunc perfuncstate, WindowStatePerAgg peraggstate)
static bool window_gettupleslot(WindowObject winobj, int64 pos, TupleTableSlot *slot)
void ExecReScanWindowAgg(WindowAggState *node)
int64 WinGetCurrentPosition(WindowObject winobj)
bool WinRowsArePeers(WindowObject winobj, int64 pos1, int64 pos2)
static TupleTableSlot * ExecWindowAgg(PlanState *pstate)
void WinSetMarkPosition(WindowObject winobj, int64 markpos)
static void eval_windowaggregates(WindowAggState *winstate)
static void release_partition(WindowAggState *winstate)
void * WinGetPartitionLocalMemory(WindowObject winobj, Size sz)
static void update_frametailpos(WindowAggState *winstate)
static void update_frameheadpos(WindowAggState *winstate)
static void initialize_windowaggregate(WindowAggState *winstate, WindowStatePerFunc perfuncstate, WindowStatePerAgg peraggstate)
static bool are_peers(WindowAggState *winstate, TupleTableSlot *slot1, TupleTableSlot *slot2)
Datum WinGetFuncArgCurrent(WindowObject winobj, int argno, bool *isnull)
int64 WinGetPartitionRowCount(WindowObject winobj)
NodeTag
Definition: nodes.h:27
#define makeNode(_type_)
Definition: nodes.h:165
#define castNode(_type_, nodeptr)
Definition: nodes.h:186
#define InvokeFunctionExecuteHook(objectId)
Definition: objectaccess.h:213
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
void build_aggregate_finalfn_expr(Oid *agg_input_types, int num_finalfn_inputs, Oid agg_state_type, Oid agg_result_type, Oid agg_input_collation, Oid finalfn_oid, Expr **finalfnexpr)
Definition: parse_agg.c:2084
Oid resolve_aggregate_transtype(Oid aggfuncid, Oid aggtranstype, Oid *inputTypes, int numArguments)
Definition: parse_agg.c:1916
void build_aggregate_transfn_expr(Oid *agg_input_types, int agg_num_inputs, int agg_num_direct_inputs, bool agg_variadic, Oid agg_state_type, Oid agg_input_collation, Oid transfn_oid, Oid invtransfn_oid, Expr **transfnexpr, Expr **invtransfnexpr)
Definition: parse_agg.c:1976
bool IsBinaryCoercible(Oid srctype, Oid targettype)
#define FRAMEOPTION_END_CURRENT_ROW
Definition: parsenodes.h:556
#define FRAMEOPTION_END_OFFSET
Definition: parsenodes.h:567
#define FRAMEOPTION_EXCLUDE_CURRENT_ROW
Definition: parsenodes.h:561
#define FRAMEOPTION_END_OFFSET_PRECEDING
Definition: parsenodes.h:558
#define FRAMEOPTION_START_UNBOUNDED_PRECEDING
Definition: parsenodes.h:551
#define FRAMEOPTION_START_CURRENT_ROW
Definition: parsenodes.h:555
#define FRAMEOPTION_START_OFFSET
Definition: parsenodes.h:565
@ OBJECT_FUNCTION
Definition: parsenodes.h:1881
#define FRAMEOPTION_EXCLUDE_TIES
Definition: parsenodes.h:563
#define FRAMEOPTION_RANGE
Definition: parsenodes.h:547
#define FRAMEOPTION_EXCLUDE_GROUP
Definition: parsenodes.h:562
#define FRAMEOPTION_GROUPS
Definition: parsenodes.h:549
#define ACL_EXECUTE
Definition: parsenodes.h:90
#define FRAMEOPTION_END_UNBOUNDED_FOLLOWING
Definition: parsenodes.h:554
#define FRAMEOPTION_START_OFFSET_PRECEDING
Definition: parsenodes.h:557
#define FRAMEOPTION_EXCLUSION
Definition: parsenodes.h:569
#define FRAMEOPTION_ROWS
Definition: parsenodes.h:548
FormData_pg_aggregate * Form_pg_aggregate
Definition: pg_aggregate.h:109
void * arg
#define FUNC_MAX_ARGS
const void size_t len
#define lfirst(lc)
Definition: pg_list.h:170
static int list_length(const List *l)
Definition: pg_list.h:150
#define NIL
Definition: pg_list.h:66
static void * list_nth(const List *list, int n)
Definition: pg_list.h:297
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
#define outerPlan(node)
Definition: plannodes.h:183
static bool DatumGetBool(Datum X)
Definition: postgres.h:438
static int64 DatumGetInt64(Datum X)
Definition: postgres.h:733
uintptr_t Datum
Definition: postgres.h:412
static Datum BoolGetDatum(bool X)
Definition: postgres.h:450
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:660
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
char * format_procedure(Oid procedure_oid)
Definition: regproc.c:323
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:255
TupleTableSlot * ecxt_innertuple
Definition: execnodes.h:249
Datum * ecxt_aggvalues
Definition: execnodes.h:266
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:247
bool * ecxt_aggnulls
Definition: execnodes.h:268
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:254
TupleTableSlot * ecxt_outertuple
Definition: execnodes.h:251
Expr * expr
Definition: execnodes.h:110
Definition: fmgr.h:57
bool fn_strict
Definition: fmgr.h:61
Definition: pg_list.h:52
Definition: nodes.h:118
bool outeropsset
Definition: execnodes.h:1112
const TupleTableSlotOps * outerops
Definition: execnodes.h:1104
ExprState * qual
Definition: execnodes.h:1050
Plan * plan
Definition: execnodes.h:1029
bool outeropsfixed
Definition: execnodes.h:1108
EState * state
Definition: execnodes.h:1031
ExprContext * ps_ExprContext
Definition: execnodes.h:1068
ProjectionInfo * ps_ProjInfo
Definition: execnodes.h:1069
ExecProcNodeMtd ExecProcNode
Definition: execnodes.h:1035
List * qual
Definition: plannodes.h:154
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1457
PlanState ps
Definition: execnodes.h:1454
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:124
ExprState * endOffset
Definition: execnodes.h:2483
MemoryContext aggcontext
Definition: execnodes.h:2502
ScanState ss
Definition: execnodes.h:2455
int64 aggregatedbase
Definition: execnodes.h:2477
int64 frametailgroup
Definition: execnodes.h:2497
int64 frameheadgroup
Definition: execnodes.h:2496
WindowStatePerAgg peragg
Definition: execnodes.h:2463
MemoryContext partcontext
Definition: execnodes.h:2501
FmgrInfo endInRangeFunc
Definition: execnodes.h:2489
TupleTableSlot * framehead_slot
Definition: execnodes.h:2530
bool frametail_valid
Definition: execnodes.h:2523
bool partition_spooled
Definition: execnodes.h:2517
FmgrInfo startInRangeFunc
Definition: execnodes.h:2488
int64 spooled_rows
Definition: execnodes.h:2471
int64 frameheadpos
Definition: execnodes.h:2473
bool more_partitions
Definition: execnodes.h:2519
Datum startOffsetValue
Definition: execnodes.h:2484
int64 grouptailpos
Definition: execnodes.h:2499
int64 currentgroup
Definition: execnodes.h:2495
TupleTableSlot * frametail_slot
Definition: execnodes.h:2531
ExprState * ordEqfunction
Definition: execnodes.h:2465
ExprState * runcondition
Definition: execnodes.h:2506
TupleTableSlot * temp_slot_2
Definition: execnodes.h:2536
Tuplestorestate * buffer
Definition: execnodes.h:2466
WindowAggStatus status
Definition: execnodes.h:2479
TupleTableSlot * agg_row_slot
Definition: execnodes.h:2534
struct WindowObjectData * agg_winobj
Definition: execnodes.h:2476
WindowStatePerFunc perfunc
Definition: execnodes.h:2462
bool framehead_valid
Definition: execnodes.h:2521
int64 groupheadpos
Definition: execnodes.h:2498
MemoryContext curaggcontext
Definition: execnodes.h:2503
bool inRangeNullsFirst
Definition: execnodes.h:2492
bool grouptail_valid
Definition: execnodes.h:2525
Datum endOffsetValue
Definition: execnodes.h:2485
int64 currentpos
Definition: execnodes.h:2472
ExprState * partEqfunction
Definition: execnodes.h:2464
int64 frametailpos
Definition: execnodes.h:2474
ExprState * startOffset
Definition: execnodes.h:2482
TupleTableSlot * first_part_slot
Definition: execnodes.h:2528
int64 aggregatedupto
Definition: execnodes.h:2478
ExprContext * tmpcontext
Definition: execnodes.h:2504
TupleTableSlot * temp_slot_1
Definition: execnodes.h:2535
bool use_pass_through
Definition: execnodes.h:2511
int partNumCols
Definition: plannodes.h:1042
Oid endInRangeFunc
Definition: plannodes.h:1086
Node * endOffset
Definition: plannodes.h:1072
bool topWindow
Definition: plannodes.h:1101
Plan plan
Definition: plannodes.h:1036
Oid inRangeColl
Definition: plannodes.h:1089
Node * startOffset
Definition: plannodes.h:1069
List * runCondition
Definition: plannodes.h:1075
Oid startInRangeFunc
Definition: plannodes.h:1083
bool inRangeAsc
Definition: plannodes.h:1092
Index winref
Definition: plannodes.h:1039
bool inRangeNullsFirst
Definition: plannodes.h:1095
int ordNumCols
Definition: plannodes.h:1054
int frameOptions
Definition: plannodes.h:1066
WindowFunc * wfunc
Definition: execnodes.h:855
ExprState * aggfilter
Definition: execnodes.h:857
bool winagg
Definition: primnodes.h:497
Oid inputcollid
Definition: primnodes.h:492
List * args
Definition: primnodes.h:493
Index winref
Definition: primnodes.h:495
Oid winfnoid
Definition: primnodes.h:489
Oid wintype
Definition: primnodes.h:490
WindowAggState * winstate
Definition: nodeWindowAgg.c:64
MemoryContext aggcontext
WindowFuncExprState * wfuncstate
Definition: nodeWindowAgg.c:80
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1434
@ AGGFNOID
Definition: syscache.h:34
@ PROCOID
Definition: syscache.h:79
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
void tuplestore_puttupleslot(Tuplestorestate *state, TupleTableSlot *slot)
Definition: tuplestore.c:708
void tuplestore_select_read_pointer(Tuplestorestate *state, int ptr)
Definition: tuplestore.c:473
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
int tuplestore_alloc_read_pointer(Tuplestorestate *state, int eflags)
Definition: tuplestore.c:383
void tuplestore_trim(Tuplestorestate *state)
Definition: tuplestore.c:1360
bool tuplestore_advance(Tuplestorestate *state, bool forward)
Definition: tuplestore.c:1110
bool tuplestore_in_memory(Tuplestorestate *state)
Definition: tuplestore.c:1455
void tuplestore_end(Tuplestorestate *state)
Definition: tuplestore.c:453
void tuplestore_set_eflags(Tuplestorestate *state, int eflags)
Definition: tuplestore.c:359
bool tuplestore_skiptuples(Tuplestorestate *state, int64 ntuples, bool forward)
Definition: tuplestore.c:1135
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:433
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:483
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:389
#define TupIsNull(slot)
Definition: tuptable.h:300
#define WINDOW_SEEK_TAIL
Definition: windowapi.h:34
#define WINDOW_SEEK_HEAD
Definition: windowapi.h:33
#define WindowObjectIsValid(winobj)
Definition: windowapi.h:41
#define WINDOW_SEEK_CURRENT
Definition: windowapi.h:32