xref: /sqlite-3.40.0/src/window.c (revision 00bd55e1)
1 /*
2 ** 2018 May 08
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 */
13 #include "sqliteInt.h"
14 
15 #ifndef SQLITE_OMIT_WINDOWFUNC
16 
17 /*
18 ** SELECT REWRITING
19 **
20 **   Any SELECT statement that contains one or more window functions in
21 **   either the select list or ORDER BY clause (the only two places window
22 **   functions may be used) is transformed by function sqlite3WindowRewrite()
23 **   in order to support window function processing. For example, with the
24 **   schema:
25 **
26 **     CREATE TABLE t1(a, b, c, d, e, f, g);
27 **
28 **   the statement:
29 **
30 **     SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e;
31 **
32 **   is transformed to:
33 **
34 **     SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM (
35 **         SELECT a, e, c, d, b FROM t1 ORDER BY c, d
36 **     ) ORDER BY e;
37 **
38 **   The flattening optimization is disabled when processing this transformed
39 **   SELECT statement. This allows the implementation of the window function
40 **   (in this case max()) to process rows sorted in order of (c, d), which
41 **   makes things easier for obvious reasons. More generally:
42 **
43 **     * FROM, WHERE, GROUP BY and HAVING clauses are all moved to
44 **       the sub-query.
45 **
46 **     * ORDER BY, LIMIT and OFFSET remain part of the parent query.
47 **
48 **     * Terminals from each of the expression trees that make up the
49 **       select-list and ORDER BY expressions in the parent query are
50 **       selected by the sub-query. For the purposes of the transformation,
51 **       terminals are column references and aggregate functions.
52 **
53 **   If there is more than one window function in the SELECT that uses
54 **   the same window declaration (the OVER bit), then a single scan may
55 **   be used to process more than one window function. For example:
56 **
57 **     SELECT max(b) OVER (PARTITION BY c ORDER BY d),
58 **            min(e) OVER (PARTITION BY c ORDER BY d)
59 **     FROM t1;
60 **
61 **   is transformed in the same way as the example above. However:
62 **
63 **     SELECT max(b) OVER (PARTITION BY c ORDER BY d),
64 **            min(e) OVER (PARTITION BY a ORDER BY b)
65 **     FROM t1;
66 **
67 **   Must be transformed to:
68 **
69 **     SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM (
70 **         SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM
71 **           SELECT a, e, c, d, b FROM t1 ORDER BY a, b
72 **         ) ORDER BY c, d
73 **     ) ORDER BY e;
74 **
75 **   so that both min() and max() may process rows in the order defined by
76 **   their respective window declarations.
77 **
78 ** INTERFACE WITH SELECT.C
79 **
80 **   When processing the rewritten SELECT statement, code in select.c calls
81 **   sqlite3WhereBegin() to begin iterating through the results of the
82 **   sub-query, which is always implemented as a co-routine. It then calls
83 **   sqlite3WindowCodeStep() to process rows and finish the scan by calling
84 **   sqlite3WhereEnd().
85 **
86 **   sqlite3WindowCodeStep() generates VM code so that, for each row returned
87 **   by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked.
88 **   When the sub-routine is invoked:
89 **
90 **     * The results of all window-functions for the row are stored
91 **       in the associated Window.regResult registers.
92 **
93 **     * The required terminal values are stored in the current row of
94 **       temp table Window.iEphCsr.
95 **
96 **   In some cases, depending on the window frame and the specific window
97 **   functions invoked, sqlite3WindowCodeStep() caches each entire partition
98 **   in a temp table before returning any rows. In other cases it does not.
99 **   This detail is encapsulated within this file, the code generated by
100 **   select.c is the same in either case.
101 **
102 ** BUILT-IN WINDOW FUNCTIONS
103 **
104 **   This implementation features the following built-in window functions:
105 **
106 **     row_number()
107 **     rank()
108 **     dense_rank()
109 **     percent_rank()
110 **     cume_dist()
111 **     ntile(N)
112 **     lead(expr [, offset [, default]])
113 **     lag(expr [, offset [, default]])
114 **     first_value(expr)
115 **     last_value(expr)
116 **     nth_value(expr, N)
117 **
118 **   These are the same built-in window functions supported by Postgres.
119 **   Although the behaviour of aggregate window functions (functions that
120 **   can be used as either aggregates or window funtions) allows them to
121 **   be implemented using an API, built-in window functions are much more
122 **   esoteric. Additionally, some window functions (e.g. nth_value())
123 **   may only be implemented by caching the entire partition in memory.
124 **   As such, some built-in window functions use the same API as aggregate
125 **   window functions and some are implemented directly using VDBE
126 **   instructions. Additionally, for those functions that use the API, the
127 **   window frame is sometimes modified before the SELECT statement is
128 **   rewritten. For example, regardless of the specified window frame, the
129 **   row_number() function always uses:
130 **
131 **     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
132 **
133 **   See sqlite3WindowUpdate() for details.
134 **
135 **   As well as some of the built-in window functions, aggregate window
136 **   functions min() and max() are implemented using VDBE instructions if
137 **   the start of the window frame is declared as anything other than
138 **   UNBOUNDED PRECEDING.
139 */
140 
141 /*
142 ** Implementation of built-in window function row_number(). Assumes that the
143 ** window frame has been coerced to:
144 **
145 **   ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
146 */
147 static void row_numberStepFunc(
148   sqlite3_context *pCtx,
149   int nArg,
150   sqlite3_value **apArg
151 ){
152   i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
153   if( p ) (*p)++;
154   UNUSED_PARAMETER(nArg);
155   UNUSED_PARAMETER(apArg);
156 }
157 static void row_numberValueFunc(sqlite3_context *pCtx){
158   i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
159   sqlite3_result_int64(pCtx, (p ? *p : 0));
160 }
161 
162 /*
163 ** Context object type used by rank(), dense_rank(), percent_rank() and
164 ** cume_dist().
165 */
166 struct CallCount {
167   i64 nValue;
168   i64 nStep;
169   i64 nTotal;
170 };
171 
172 /*
173 ** Implementation of built-in window function dense_rank(). Assumes that
174 ** the window frame has been set to:
175 **
176 **   RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
177 */
178 static void dense_rankStepFunc(
179   sqlite3_context *pCtx,
180   int nArg,
181   sqlite3_value **apArg
182 ){
183   struct CallCount *p;
184   p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
185   if( p ) p->nStep = 1;
186   UNUSED_PARAMETER(nArg);
187   UNUSED_PARAMETER(apArg);
188 }
189 static void dense_rankValueFunc(sqlite3_context *pCtx){
190   struct CallCount *p;
191   p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
192   if( p ){
193     if( p->nStep ){
194       p->nValue++;
195       p->nStep = 0;
196     }
197     sqlite3_result_int64(pCtx, p->nValue);
198   }
199 }
200 
201 /*
202 ** Implementation of built-in window function nth_value(). This
203 ** implementation is used in "slow mode" only - when the EXCLUDE clause
204 ** is not set to the default value "NO OTHERS".
205 */
206 struct NthValueCtx {
207   i64 nStep;
208   sqlite3_value *pValue;
209 };
210 static void nth_valueStepFunc(
211   sqlite3_context *pCtx,
212   int nArg,
213   sqlite3_value **apArg
214 ){
215   struct NthValueCtx *p;
216   p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
217   if( p ){
218     i64 iVal;
219     switch( sqlite3_value_numeric_type(apArg[1]) ){
220       case SQLITE_INTEGER:
221         iVal = sqlite3_value_int64(apArg[1]);
222         break;
223       case SQLITE_FLOAT: {
224         double fVal = sqlite3_value_double(apArg[1]);
225         if( ((i64)fVal)!=fVal ) goto error_out;
226         iVal = (i64)fVal;
227         break;
228       }
229       default:
230         goto error_out;
231     }
232     if( iVal<=0 ) goto error_out;
233 
234     p->nStep++;
235     if( iVal==p->nStep ){
236       p->pValue = sqlite3_value_dup(apArg[0]);
237       if( !p->pValue ){
238         sqlite3_result_error_nomem(pCtx);
239       }
240     }
241   }
242   UNUSED_PARAMETER(nArg);
243   UNUSED_PARAMETER(apArg);
244   return;
245 
246  error_out:
247   sqlite3_result_error(
248       pCtx, "second argument to nth_value must be a positive integer", -1
249   );
250 }
251 static void nth_valueFinalizeFunc(sqlite3_context *pCtx){
252   struct NthValueCtx *p;
253   p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, 0);
254   if( p && p->pValue ){
255     sqlite3_result_value(pCtx, p->pValue);
256     sqlite3_value_free(p->pValue);
257     p->pValue = 0;
258   }
259 }
260 #define nth_valueInvFunc noopStepFunc
261 #define nth_valueValueFunc noopValueFunc
262 
263 static void first_valueStepFunc(
264   sqlite3_context *pCtx,
265   int nArg,
266   sqlite3_value **apArg
267 ){
268   struct NthValueCtx *p;
269   p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
270   if( p && p->pValue==0 ){
271     p->pValue = sqlite3_value_dup(apArg[0]);
272     if( !p->pValue ){
273       sqlite3_result_error_nomem(pCtx);
274     }
275   }
276   UNUSED_PARAMETER(nArg);
277   UNUSED_PARAMETER(apArg);
278 }
279 static void first_valueFinalizeFunc(sqlite3_context *pCtx){
280   struct NthValueCtx *p;
281   p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
282   if( p && p->pValue ){
283     sqlite3_result_value(pCtx, p->pValue);
284     sqlite3_value_free(p->pValue);
285     p->pValue = 0;
286   }
287 }
288 #define first_valueInvFunc noopStepFunc
289 #define first_valueValueFunc noopValueFunc
290 
291 /*
292 ** Implementation of built-in window function rank(). Assumes that
293 ** the window frame has been set to:
294 **
295 **   RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
296 */
297 static void rankStepFunc(
298   sqlite3_context *pCtx,
299   int nArg,
300   sqlite3_value **apArg
301 ){
302   struct CallCount *p;
303   p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
304   if( p ){
305     p->nStep++;
306     if( p->nValue==0 ){
307       p->nValue = p->nStep;
308     }
309   }
310   UNUSED_PARAMETER(nArg);
311   UNUSED_PARAMETER(apArg);
312 }
313 static void rankValueFunc(sqlite3_context *pCtx){
314   struct CallCount *p;
315   p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
316   if( p ){
317     sqlite3_result_int64(pCtx, p->nValue);
318     p->nValue = 0;
319   }
320 }
321 
322 /*
323 ** Implementation of built-in window function percent_rank(). Assumes that
324 ** the window frame has been set to:
325 **
326 **   GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
327 */
328 static void percent_rankStepFunc(
329   sqlite3_context *pCtx,
330   int nArg,
331   sqlite3_value **apArg
332 ){
333   struct CallCount *p;
334   UNUSED_PARAMETER(nArg); assert( nArg==0 );
335   UNUSED_PARAMETER(apArg);
336   p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
337   if( p ){
338     p->nTotal++;
339   }
340 }
341 static void percent_rankInvFunc(
342   sqlite3_context *pCtx,
343   int nArg,
344   sqlite3_value **apArg
345 ){
346   struct CallCount *p;
347   UNUSED_PARAMETER(nArg); assert( nArg==0 );
348   UNUSED_PARAMETER(apArg);
349   p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
350   p->nStep++;
351 }
352 static void percent_rankValueFunc(sqlite3_context *pCtx){
353   struct CallCount *p;
354   p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
355   if( p ){
356     p->nValue = p->nStep;
357     if( p->nTotal>1 ){
358       double r = (double)p->nValue / (double)(p->nTotal-1);
359       sqlite3_result_double(pCtx, r);
360     }else{
361       sqlite3_result_double(pCtx, 0.0);
362     }
363   }
364 }
365 #define percent_rankFinalizeFunc percent_rankValueFunc
366 
367 /*
368 ** Implementation of built-in window function cume_dist(). Assumes that
369 ** the window frame has been set to:
370 **
371 **   GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
372 */
373 static void cume_distStepFunc(
374   sqlite3_context *pCtx,
375   int nArg,
376   sqlite3_value **apArg
377 ){
378   struct CallCount *p;
379   UNUSED_PARAMETER(nArg); assert( nArg==0 );
380   UNUSED_PARAMETER(apArg);
381   p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
382   if( p ){
383     p->nTotal++;
384   }
385 }
386 static void cume_distInvFunc(
387   sqlite3_context *pCtx,
388   int nArg,
389   sqlite3_value **apArg
390 ){
391   struct CallCount *p;
392   UNUSED_PARAMETER(nArg); assert( nArg==0 );
393   UNUSED_PARAMETER(apArg);
394   p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
395   p->nStep++;
396 }
397 static void cume_distValueFunc(sqlite3_context *pCtx){
398   struct CallCount *p;
399   p = (struct CallCount*)sqlite3_aggregate_context(pCtx, 0);
400   if( p ){
401     double r = (double)(p->nStep) / (double)(p->nTotal);
402     sqlite3_result_double(pCtx, r);
403   }
404 }
405 #define cume_distFinalizeFunc cume_distValueFunc
406 
407 /*
408 ** Context object for ntile() window function.
409 */
410 struct NtileCtx {
411   i64 nTotal;                     /* Total rows in partition */
412   i64 nParam;                     /* Parameter passed to ntile(N) */
413   i64 iRow;                       /* Current row */
414 };
415 
416 /*
417 ** Implementation of ntile(). This assumes that the window frame has
418 ** been coerced to:
419 **
420 **   ROWS CURRENT ROW AND UNBOUNDED FOLLOWING
421 */
422 static void ntileStepFunc(
423   sqlite3_context *pCtx,
424   int nArg,
425   sqlite3_value **apArg
426 ){
427   struct NtileCtx *p;
428   assert( nArg==1 ); UNUSED_PARAMETER(nArg);
429   p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
430   if( p ){
431     if( p->nTotal==0 ){
432       p->nParam = sqlite3_value_int64(apArg[0]);
433       if( p->nParam<=0 ){
434         sqlite3_result_error(
435             pCtx, "argument of ntile must be a positive integer", -1
436         );
437       }
438     }
439     p->nTotal++;
440   }
441 }
442 static void ntileInvFunc(
443   sqlite3_context *pCtx,
444   int nArg,
445   sqlite3_value **apArg
446 ){
447   struct NtileCtx *p;
448   assert( nArg==1 ); UNUSED_PARAMETER(nArg);
449   UNUSED_PARAMETER(apArg);
450   p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
451   p->iRow++;
452 }
453 static void ntileValueFunc(sqlite3_context *pCtx){
454   struct NtileCtx *p;
455   p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
456   if( p && p->nParam>0 ){
457     int nSize = (p->nTotal / p->nParam);
458     if( nSize==0 ){
459       sqlite3_result_int64(pCtx, p->iRow+1);
460     }else{
461       i64 nLarge = p->nTotal - p->nParam*nSize;
462       i64 iSmall = nLarge*(nSize+1);
463       i64 iRow = p->iRow;
464 
465       assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
466 
467       if( iRow<iSmall ){
468         sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
469       }else{
470         sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
471       }
472     }
473   }
474 }
475 #define ntileFinalizeFunc ntileValueFunc
476 
477 /*
478 ** Context object for last_value() window function.
479 */
480 struct LastValueCtx {
481   sqlite3_value *pVal;
482   int nVal;
483 };
484 
485 /*
486 ** Implementation of last_value().
487 */
488 static void last_valueStepFunc(
489   sqlite3_context *pCtx,
490   int nArg,
491   sqlite3_value **apArg
492 ){
493   struct LastValueCtx *p;
494   UNUSED_PARAMETER(nArg);
495   p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
496   if( p ){
497     sqlite3_value_free(p->pVal);
498     p->pVal = sqlite3_value_dup(apArg[0]);
499     if( p->pVal==0 ){
500       sqlite3_result_error_nomem(pCtx);
501     }else{
502       p->nVal++;
503     }
504   }
505 }
506 static void last_valueInvFunc(
507   sqlite3_context *pCtx,
508   int nArg,
509   sqlite3_value **apArg
510 ){
511   struct LastValueCtx *p;
512   UNUSED_PARAMETER(nArg);
513   UNUSED_PARAMETER(apArg);
514   p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
515   if( ALWAYS(p) ){
516     p->nVal--;
517     if( p->nVal==0 ){
518       sqlite3_value_free(p->pVal);
519       p->pVal = 0;
520     }
521   }
522 }
523 static void last_valueValueFunc(sqlite3_context *pCtx){
524   struct LastValueCtx *p;
525   p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, 0);
526   if( p && p->pVal ){
527     sqlite3_result_value(pCtx, p->pVal);
528   }
529 }
530 static void last_valueFinalizeFunc(sqlite3_context *pCtx){
531   struct LastValueCtx *p;
532   p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
533   if( p && p->pVal ){
534     sqlite3_result_value(pCtx, p->pVal);
535     sqlite3_value_free(p->pVal);
536     p->pVal = 0;
537   }
538 }
539 
540 /*
541 ** Static names for the built-in window function names.  These static
542 ** names are used, rather than string literals, so that FuncDef objects
543 ** can be associated with a particular window function by direct
544 ** comparison of the zName pointer.  Example:
545 **
546 **       if( pFuncDef->zName==row_valueName ){ ... }
547 */
548 static const char row_numberName[] =   "row_number";
549 static const char dense_rankName[] =   "dense_rank";
550 static const char rankName[] =         "rank";
551 static const char percent_rankName[] = "percent_rank";
552 static const char cume_distName[] =    "cume_dist";
553 static const char ntileName[] =        "ntile";
554 static const char last_valueName[] =   "last_value";
555 static const char nth_valueName[] =    "nth_value";
556 static const char first_valueName[] =  "first_value";
557 static const char leadName[] =         "lead";
558 static const char lagName[] =          "lag";
559 
560 /*
561 ** No-op implementations of xStep() and xFinalize().  Used as place-holders
562 ** for built-in window functions that never call those interfaces.
563 **
564 ** The noopValueFunc() is called but is expected to do nothing.  The
565 ** noopStepFunc() is never called, and so it is marked with NO_TEST to
566 ** let the test coverage routine know not to expect this function to be
567 ** invoked.
568 */
569 static void noopStepFunc(    /*NO_TEST*/
570   sqlite3_context *p,        /*NO_TEST*/
571   int n,                     /*NO_TEST*/
572   sqlite3_value **a          /*NO_TEST*/
573 ){                           /*NO_TEST*/
574   UNUSED_PARAMETER(p);       /*NO_TEST*/
575   UNUSED_PARAMETER(n);       /*NO_TEST*/
576   UNUSED_PARAMETER(a);       /*NO_TEST*/
577   assert(0);                 /*NO_TEST*/
578 }                            /*NO_TEST*/
579 static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
580 
581 /* Window functions that use all window interfaces: xStep, xFinal,
582 ** xValue, and xInverse */
583 #define WINDOWFUNCALL(name,nArg,extra) {                                   \
584   nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,                      \
585   name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc,               \
586   name ## InvFunc, name ## Name, {0}                                       \
587 }
588 
589 /* Window functions that are implemented using bytecode and thus have
590 ** no-op routines for their methods */
591 #define WINDOWFUNCNOOP(name,nArg,extra) {                                  \
592   nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,                      \
593   noopStepFunc, noopValueFunc, noopValueFunc,                              \
594   noopStepFunc, name ## Name, {0}                                          \
595 }
596 
597 /* Window functions that use all window interfaces: xStep, the
598 ** same routine for xFinalize and xValue and which never call
599 ** xInverse. */
600 #define WINDOWFUNCX(name,nArg,extra) {                                     \
601   nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0,                      \
602   name ## StepFunc, name ## ValueFunc, name ## ValueFunc,                  \
603   noopStepFunc, name ## Name, {0}                                          \
604 }
605 
606 
607 /*
608 ** Register those built-in window functions that are not also aggregates.
609 */
610 void sqlite3WindowFunctions(void){
611   static FuncDef aWindowFuncs[] = {
612     WINDOWFUNCX(row_number, 0, 0),
613     WINDOWFUNCX(dense_rank, 0, 0),
614     WINDOWFUNCX(rank, 0, 0),
615     WINDOWFUNCALL(percent_rank, 0, 0),
616     WINDOWFUNCALL(cume_dist, 0, 0),
617     WINDOWFUNCALL(ntile, 1, 0),
618     WINDOWFUNCALL(last_value, 1, 0),
619     WINDOWFUNCALL(nth_value, 2, 0),
620     WINDOWFUNCALL(first_value, 1, 0),
621     WINDOWFUNCNOOP(lead, 1, 0),
622     WINDOWFUNCNOOP(lead, 2, 0),
623     WINDOWFUNCNOOP(lead, 3, 0),
624     WINDOWFUNCNOOP(lag, 1, 0),
625     WINDOWFUNCNOOP(lag, 2, 0),
626     WINDOWFUNCNOOP(lag, 3, 0),
627   };
628   sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
629 }
630 
631 static Window *windowFind(Parse *pParse, Window *pList, const char *zName){
632   Window *p;
633   for(p=pList; p; p=p->pNextWin){
634     if( sqlite3StrICmp(p->zName, zName)==0 ) break;
635   }
636   if( p==0 ){
637     sqlite3ErrorMsg(pParse, "no such window: %s", zName);
638   }
639   return p;
640 }
641 
642 /*
643 ** This function is called immediately after resolving the function name
644 ** for a window function within a SELECT statement. Argument pList is a
645 ** linked list of WINDOW definitions for the current SELECT statement.
646 ** Argument pFunc is the function definition just resolved and pWin
647 ** is the Window object representing the associated OVER clause. This
648 ** function updates the contents of pWin as follows:
649 **
650 **   * If the OVER clause refered to a named window (as in "max(x) OVER win"),
651 **     search list pList for a matching WINDOW definition, and update pWin
652 **     accordingly. If no such WINDOW clause can be found, leave an error
653 **     in pParse.
654 **
655 **   * If the function is a built-in window function that requires the
656 **     window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
657 **     of this file), pWin is updated here.
658 */
659 void sqlite3WindowUpdate(
660   Parse *pParse,
661   Window *pList,                  /* List of named windows for this SELECT */
662   Window *pWin,                   /* Window frame to update */
663   FuncDef *pFunc                  /* Window function definition */
664 ){
665   if( pWin->zName && pWin->eFrmType==0 ){
666     Window *p = windowFind(pParse, pList, pWin->zName);
667     if( p==0 ) return;
668     pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
669     pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
670     pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
671     pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
672     pWin->eStart = p->eStart;
673     pWin->eEnd = p->eEnd;
674     pWin->eFrmType = p->eFrmType;
675     pWin->eExclude = p->eExclude;
676   }else{
677     sqlite3WindowChain(pParse, pWin, pList);
678   }
679   if( (pWin->eFrmType==TK_RANGE)
680    && (pWin->pStart || pWin->pEnd)
681    && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)
682   ){
683     sqlite3ErrorMsg(pParse,
684       "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression"
685     );
686   }else
687   if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
688     sqlite3 *db = pParse->db;
689     if( pWin->pFilter ){
690       sqlite3ErrorMsg(pParse,
691           "FILTER clause may only be used with aggregate window functions"
692       );
693     }else{
694       struct WindowUpdate {
695         const char *zFunc;
696         int eFrmType;
697         int eStart;
698         int eEnd;
699       } aUp[] = {
700         { row_numberName,   TK_ROWS,   TK_UNBOUNDED, TK_CURRENT },
701         { dense_rankName,   TK_RANGE,  TK_UNBOUNDED, TK_CURRENT },
702         { rankName,         TK_RANGE,  TK_UNBOUNDED, TK_CURRENT },
703         { percent_rankName, TK_GROUPS, TK_CURRENT,   TK_UNBOUNDED },
704         { cume_distName,    TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED },
705         { ntileName,        TK_ROWS,   TK_CURRENT,   TK_UNBOUNDED },
706         { leadName,         TK_ROWS,   TK_UNBOUNDED, TK_UNBOUNDED },
707         { lagName,          TK_ROWS,   TK_UNBOUNDED, TK_CURRENT },
708       };
709       int i;
710       for(i=0; i<ArraySize(aUp); i++){
711         if( pFunc->zName==aUp[i].zFunc ){
712           sqlite3ExprDelete(db, pWin->pStart);
713           sqlite3ExprDelete(db, pWin->pEnd);
714           pWin->pEnd = pWin->pStart = 0;
715           pWin->eFrmType = aUp[i].eFrmType;
716           pWin->eStart = aUp[i].eStart;
717           pWin->eEnd = aUp[i].eEnd;
718           pWin->eExclude = 0;
719           if( pWin->eStart==TK_FOLLOWING ){
720             pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1");
721           }
722           break;
723         }
724       }
725     }
726   }
727   pWin->pFunc = pFunc;
728 }
729 
730 /*
731 ** Context object passed through sqlite3WalkExprList() to
732 ** selectWindowRewriteExprCb() by selectWindowRewriteEList().
733 */
734 typedef struct WindowRewrite WindowRewrite;
735 struct WindowRewrite {
736   Window *pWin;
737   SrcList *pSrc;
738   ExprList *pSub;
739   Table *pTab;
740   Select *pSubSelect;             /* Current sub-select, if any */
741 };
742 
743 /*
744 ** Callback function used by selectWindowRewriteEList(). If necessary,
745 ** this function appends to the output expression-list and updates
746 ** expression (*ppExpr) in place.
747 */
748 static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
749   struct WindowRewrite *p = pWalker->u.pRewrite;
750   Parse *pParse = pWalker->pParse;
751   assert( p!=0 );
752   assert( p->pWin!=0 );
753 
754   /* If this function is being called from within a scalar sub-select
755   ** that used by the SELECT statement being processed, only process
756   ** TK_COLUMN expressions that refer to it (the outer SELECT). Do
757   ** not process aggregates or window functions at all, as they belong
758   ** to the scalar sub-select.  */
759   if( p->pSubSelect ){
760     if( pExpr->op!=TK_COLUMN ){
761       return WRC_Continue;
762     }else{
763       int nSrc = p->pSrc->nSrc;
764       int i;
765       for(i=0; i<nSrc; i++){
766         if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
767       }
768       if( i==nSrc ) return WRC_Continue;
769     }
770   }
771 
772   switch( pExpr->op ){
773 
774     case TK_FUNCTION:
775       if( !ExprHasProperty(pExpr, EP_WinFunc) ){
776         break;
777       }else{
778         Window *pWin;
779         for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
780           if( pExpr->y.pWin==pWin ){
781             assert( pWin->pOwner==pExpr );
782             return WRC_Prune;
783           }
784         }
785       }
786       /* Fall through.  */
787 
788     case TK_AGG_FUNCTION:
789     case TK_COLUMN: {
790       int iCol = -1;
791       if( p->pSub ){
792         int i;
793         for(i=0; i<p->pSub->nExpr; i++){
794           if( 0==sqlite3ExprCompare(0, p->pSub->a[i].pExpr, pExpr, -1) ){
795             iCol = i;
796             break;
797           }
798         }
799       }
800       if( iCol<0 ){
801         Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
802         if( pDup && pDup->op==TK_AGG_FUNCTION ) pDup->op = TK_FUNCTION;
803         p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
804       }
805       if( p->pSub ){
806         assert( ExprHasProperty(pExpr, EP_Static)==0 );
807         ExprSetProperty(pExpr, EP_Static);
808         sqlite3ExprDelete(pParse->db, pExpr);
809         ExprClearProperty(pExpr, EP_Static);
810         memset(pExpr, 0, sizeof(Expr));
811 
812         pExpr->op = TK_COLUMN;
813         pExpr->iColumn = (iCol<0 ? p->pSub->nExpr-1: iCol);
814         pExpr->iTable = p->pWin->iEphCsr;
815         pExpr->y.pTab = p->pTab;
816       }
817       if( pParse->db->mallocFailed ) return WRC_Abort;
818       break;
819     }
820 
821     default: /* no-op */
822       break;
823   }
824 
825   return WRC_Continue;
826 }
827 static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
828   struct WindowRewrite *p = pWalker->u.pRewrite;
829   Select *pSave = p->pSubSelect;
830   if( pSave==pSelect ){
831     return WRC_Continue;
832   }else{
833     p->pSubSelect = pSelect;
834     sqlite3WalkSelect(pWalker, pSelect);
835     p->pSubSelect = pSave;
836   }
837   return WRC_Prune;
838 }
839 
840 
841 /*
842 ** Iterate through each expression in expression-list pEList. For each:
843 **
844 **   * TK_COLUMN,
845 **   * aggregate function, or
846 **   * window function with a Window object that is not a member of the
847 **     Window list passed as the second argument (pWin).
848 **
849 ** Append the node to output expression-list (*ppSub). And replace it
850 ** with a TK_COLUMN that reads the (N-1)th element of table
851 ** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
852 ** appending the new one.
853 */
854 static void selectWindowRewriteEList(
855   Parse *pParse,
856   Window *pWin,
857   SrcList *pSrc,
858   ExprList *pEList,               /* Rewrite expressions in this list */
859   Table *pTab,
860   ExprList **ppSub                /* IN/OUT: Sub-select expression-list */
861 ){
862   Walker sWalker;
863   WindowRewrite sRewrite;
864 
865   assert( pWin!=0 );
866   memset(&sWalker, 0, sizeof(Walker));
867   memset(&sRewrite, 0, sizeof(WindowRewrite));
868 
869   sRewrite.pSub = *ppSub;
870   sRewrite.pWin = pWin;
871   sRewrite.pSrc = pSrc;
872   sRewrite.pTab = pTab;
873 
874   sWalker.pParse = pParse;
875   sWalker.xExprCallback = selectWindowRewriteExprCb;
876   sWalker.xSelectCallback = selectWindowRewriteSelectCb;
877   sWalker.u.pRewrite = &sRewrite;
878 
879   (void)sqlite3WalkExprList(&sWalker, pEList);
880 
881   *ppSub = sRewrite.pSub;
882 }
883 
884 /*
885 ** Append a copy of each expression in expression-list pAppend to
886 ** expression list pList. Return a pointer to the result list.
887 */
888 static ExprList *exprListAppendList(
889   Parse *pParse,          /* Parsing context */
890   ExprList *pList,        /* List to which to append. Might be NULL */
891   ExprList *pAppend,      /* List of values to append. Might be NULL */
892   int bIntToNull
893 ){
894   if( pAppend ){
895     int i;
896     int nInit = pList ? pList->nExpr : 0;
897     for(i=0; i<pAppend->nExpr; i++){
898       int iDummy;
899       Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
900       assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );
901       if( bIntToNull && pDup && sqlite3ExprIsInteger(pDup, &iDummy) ){
902         pDup->op = TK_NULL;
903         pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
904         pDup->u.zToken = 0;
905       }
906       pList = sqlite3ExprListAppend(pParse, pList, pDup);
907       if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;
908     }
909   }
910   return pList;
911 }
912 
913 /*
914 ** If the SELECT statement passed as the second argument does not invoke
915 ** any SQL window functions, this function is a no-op. Otherwise, it
916 ** rewrites the SELECT statement so that window function xStep functions
917 ** are invoked in the correct order as described under "SELECT REWRITING"
918 ** at the top of this file.
919 */
920 int sqlite3WindowRewrite(Parse *pParse, Select *p){
921   int rc = SQLITE_OK;
922   if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){
923     Vdbe *v = sqlite3GetVdbe(pParse);
924     sqlite3 *db = pParse->db;
925     Select *pSub = 0;             /* The subquery */
926     SrcList *pSrc = p->pSrc;
927     Expr *pWhere = p->pWhere;
928     ExprList *pGroupBy = p->pGroupBy;
929     Expr *pHaving = p->pHaving;
930     ExprList *pSort = 0;
931 
932     ExprList *pSublist = 0;       /* Expression list for sub-query */
933     Window *pMWin = p->pWin;      /* Master window object */
934     Window *pWin;                 /* Window object iterator */
935     Table *pTab;
936     u32 selFlags = p->selFlags;
937 
938     pTab = sqlite3DbMallocZero(db, sizeof(Table));
939     if( pTab==0 ){
940       return sqlite3ErrorToParser(db, SQLITE_NOMEM);
941     }
942 
943     p->pSrc = 0;
944     p->pWhere = 0;
945     p->pGroupBy = 0;
946     p->pHaving = 0;
947     p->selFlags &= ~SF_Aggregate;
948     p->selFlags |= SF_WinRewrite;
949 
950     /* Create the ORDER BY clause for the sub-select. This is the concatenation
951     ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
952     ** redundant, remove the ORDER BY from the parent SELECT.  */
953     pSort = exprListAppendList(pParse, 0, pMWin->pPartition, 1);
954     pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);
955     if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){
956       int nSave = pSort->nExpr;
957       pSort->nExpr = p->pOrderBy->nExpr;
958       if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
959         sqlite3ExprListDelete(db, p->pOrderBy);
960         p->pOrderBy = 0;
961       }
962       pSort->nExpr = nSave;
963     }
964 
965     /* Assign a cursor number for the ephemeral table used to buffer rows.
966     ** The OpenEphemeral instruction is coded later, after it is known how
967     ** many columns the table will have.  */
968     pMWin->iEphCsr = pParse->nTab++;
969     pParse->nTab += 3;
970 
971     selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);
972     selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);
973     pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
974 
975     /* Append the PARTITION BY and ORDER BY expressions to the to the
976     ** sub-select expression list. They are required to figure out where
977     ** boundaries for partitions and sets of peer rows lie.  */
978     pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);
979     pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);
980 
981     /* Append the arguments passed to each window function to the
982     ** sub-select expression list. Also allocate two registers for each
983     ** window function - one for the accumulator, another for interim
984     ** results.  */
985     for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
986       ExprList *pArgs = pWin->pOwner->x.pList;
987       if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){
988         selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);
989         pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
990         pWin->bExprArgs = 1;
991       }else{
992         pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
993         pSublist = exprListAppendList(pParse, pSublist, pArgs, 0);
994       }
995       if( pWin->pFilter ){
996         Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
997         pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
998       }
999       pWin->regAccum = ++pParse->nMem;
1000       pWin->regResult = ++pParse->nMem;
1001       sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1002     }
1003 
1004     /* If there is no ORDER BY or PARTITION BY clause, and the window
1005     ** function accepts zero arguments, and there are no other columns
1006     ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
1007     ** that pSublist is still NULL here. Add a constant expression here to
1008     ** keep everything legal in this case.
1009     */
1010     if( pSublist==0 ){
1011       pSublist = sqlite3ExprListAppend(pParse, 0,
1012         sqlite3Expr(db, TK_INTEGER, "0")
1013       );
1014     }
1015 
1016     pSub = sqlite3SelectNew(
1017         pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
1018     );
1019     p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
1020     if( p->pSrc ){
1021       Table *pTab2;
1022       p->pSrc->a[0].pSelect = pSub;
1023       sqlite3SrcListAssignCursors(pParse, p->pSrc);
1024       pSub->selFlags |= SF_Expanded;
1025       pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);
1026       pSub->selFlags |= (selFlags & SF_Aggregate);
1027       if( pTab2==0 ){
1028         /* Might actually be some other kind of error, but in that case
1029         ** pParse->nErr will be set, so if SQLITE_NOMEM is set, we will get
1030         ** the correct error message regardless. */
1031         rc = SQLITE_NOMEM;
1032       }else{
1033         memcpy(pTab, pTab2, sizeof(Table));
1034         pTab->tabFlags |= TF_Ephemeral;
1035         p->pSrc->a[0].pTab = pTab;
1036         pTab = pTab2;
1037       }
1038     }else{
1039       sqlite3SelectDelete(db, pSub);
1040     }
1041     if( db->mallocFailed ) rc = SQLITE_NOMEM;
1042     sqlite3DbFree(db, pTab);
1043   }
1044 
1045   if( rc ){
1046     if( pParse->nErr==0 ){
1047       assert( pParse->db->mallocFailed );
1048       sqlite3ErrorToParser(pParse->db, SQLITE_NOMEM);
1049     }
1050     sqlite3SelectReset(pParse, p);
1051   }
1052   return rc;
1053 }
1054 
1055 /*
1056 ** Unlink the Window object from the Select to which it is attached,
1057 ** if it is attached.
1058 */
1059 void sqlite3WindowUnlinkFromSelect(Window *p){
1060   if( p->ppThis ){
1061     *p->ppThis = p->pNextWin;
1062     if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis;
1063     p->ppThis = 0;
1064   }
1065 }
1066 
1067 /*
1068 ** Free the Window object passed as the second argument.
1069 */
1070 void sqlite3WindowDelete(sqlite3 *db, Window *p){
1071   if( p ){
1072     sqlite3WindowUnlinkFromSelect(p);
1073     sqlite3ExprDelete(db, p->pFilter);
1074     sqlite3ExprListDelete(db, p->pPartition);
1075     sqlite3ExprListDelete(db, p->pOrderBy);
1076     sqlite3ExprDelete(db, p->pEnd);
1077     sqlite3ExprDelete(db, p->pStart);
1078     sqlite3DbFree(db, p->zName);
1079     sqlite3DbFree(db, p->zBase);
1080     sqlite3DbFree(db, p);
1081   }
1082 }
1083 
1084 /*
1085 ** Free the linked list of Window objects starting at the second argument.
1086 */
1087 void sqlite3WindowListDelete(sqlite3 *db, Window *p){
1088   while( p ){
1089     Window *pNext = p->pNextWin;
1090     sqlite3WindowDelete(db, p);
1091     p = pNext;
1092   }
1093 }
1094 
1095 /*
1096 ** The argument expression is an PRECEDING or FOLLOWING offset.  The
1097 ** value should be a non-negative integer.  If the value is not a
1098 ** constant, change it to NULL.  The fact that it is then a non-negative
1099 ** integer will be caught later.  But it is important not to leave
1100 ** variable values in the expression tree.
1101 */
1102 static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
1103   if( 0==sqlite3ExprIsConstant(pExpr) ){
1104     if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
1105     sqlite3ExprDelete(pParse->db, pExpr);
1106     pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
1107   }
1108   return pExpr;
1109 }
1110 
1111 /*
1112 ** Allocate and return a new Window object describing a Window Definition.
1113 */
1114 Window *sqlite3WindowAlloc(
1115   Parse *pParse,    /* Parsing context */
1116   int eType,        /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */
1117   int eStart,       /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
1118   Expr *pStart,     /* Start window size if TK_PRECEDING or FOLLOWING */
1119   int eEnd,         /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
1120   Expr *pEnd,       /* End window size if TK_FOLLOWING or PRECEDING */
1121   u8 eExclude       /* EXCLUDE clause */
1122 ){
1123   Window *pWin = 0;
1124   int bImplicitFrame = 0;
1125 
1126   /* Parser assures the following: */
1127   assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
1128   assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
1129            || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
1130   assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
1131            || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
1132   assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
1133   assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
1134 
1135   if( eType==0 ){
1136     bImplicitFrame = 1;
1137     eType = TK_RANGE;
1138   }
1139 
1140   /* Additionally, the
1141   ** starting boundary type may not occur earlier in the following list than
1142   ** the ending boundary type:
1143   **
1144   **   UNBOUNDED PRECEDING
1145   **   <expr> PRECEDING
1146   **   CURRENT ROW
1147   **   <expr> FOLLOWING
1148   **   UNBOUNDED FOLLOWING
1149   **
1150   ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
1151   ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
1152   ** frame boundary.
1153   */
1154   if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
1155    || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
1156   ){
1157     sqlite3ErrorMsg(pParse, "unsupported frame specification");
1158     goto windowAllocErr;
1159   }
1160 
1161   pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
1162   if( pWin==0 ) goto windowAllocErr;
1163   pWin->eFrmType = eType;
1164   pWin->eStart = eStart;
1165   pWin->eEnd = eEnd;
1166   if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){
1167     eExclude = TK_NO;
1168   }
1169   pWin->eExclude = eExclude;
1170   pWin->bImplicitFrame = bImplicitFrame;
1171   pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
1172   pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
1173   return pWin;
1174 
1175 windowAllocErr:
1176   sqlite3ExprDelete(pParse->db, pEnd);
1177   sqlite3ExprDelete(pParse->db, pStart);
1178   return 0;
1179 }
1180 
1181 /*
1182 ** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
1183 ** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
1184 ** equivalent nul-terminated string.
1185 */
1186 Window *sqlite3WindowAssemble(
1187   Parse *pParse,
1188   Window *pWin,
1189   ExprList *pPartition,
1190   ExprList *pOrderBy,
1191   Token *pBase
1192 ){
1193   if( pWin ){
1194     pWin->pPartition = pPartition;
1195     pWin->pOrderBy = pOrderBy;
1196     if( pBase ){
1197       pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
1198     }
1199   }else{
1200     sqlite3ExprListDelete(pParse->db, pPartition);
1201     sqlite3ExprListDelete(pParse->db, pOrderBy);
1202   }
1203   return pWin;
1204 }
1205 
1206 /*
1207 ** Window *pWin has just been created from a WINDOW clause. Tokne pBase
1208 ** is the base window. Earlier windows from the same WINDOW clause are
1209 ** stored in the linked list starting at pWin->pNextWin. This function
1210 ** either updates *pWin according to the base specification, or else
1211 ** leaves an error in pParse.
1212 */
1213 void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
1214   if( pWin->zBase ){
1215     sqlite3 *db = pParse->db;
1216     Window *pExist = windowFind(pParse, pList, pWin->zBase);
1217     if( pExist ){
1218       const char *zErr = 0;
1219       /* Check for errors */
1220       if( pWin->pPartition ){
1221         zErr = "PARTITION clause";
1222       }else if( pExist->pOrderBy && pWin->pOrderBy ){
1223         zErr = "ORDER BY clause";
1224       }else if( pExist->bImplicitFrame==0 ){
1225         zErr = "frame specification";
1226       }
1227       if( zErr ){
1228         sqlite3ErrorMsg(pParse,
1229             "cannot override %s of window: %s", zErr, pWin->zBase
1230         );
1231       }else{
1232         pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
1233         if( pExist->pOrderBy ){
1234           assert( pWin->pOrderBy==0 );
1235           pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
1236         }
1237         sqlite3DbFree(db, pWin->zBase);
1238         pWin->zBase = 0;
1239       }
1240     }
1241   }
1242 }
1243 
1244 /*
1245 ** Attach window object pWin to expression p.
1246 */
1247 void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
1248   if( p ){
1249     assert( p->op==TK_FUNCTION );
1250     assert( pWin );
1251     p->y.pWin = pWin;
1252     ExprSetProperty(p, EP_WinFunc);
1253     pWin->pOwner = p;
1254     if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){
1255       sqlite3ErrorMsg(pParse,
1256           "DISTINCT is not supported for window functions"
1257       );
1258     }
1259   }else{
1260     sqlite3WindowDelete(pParse->db, pWin);
1261   }
1262 }
1263 
1264 /*
1265 ** Possibly link window pWin into the list at pSel->pWin (window functions
1266 ** to be processed as part of SELECT statement pSel). The window is linked
1267 ** in if either (a) there are no other windows already linked to this
1268 ** SELECT, or (b) the windows already linked use a compatible window frame.
1269 */
1270 void sqlite3WindowLink(Select *pSel, Window *pWin){
1271   if( pSel!=0
1272    && (0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0))
1273   ){
1274     pWin->pNextWin = pSel->pWin;
1275     if( pSel->pWin ){
1276       pSel->pWin->ppThis = &pWin->pNextWin;
1277     }
1278     pSel->pWin = pWin;
1279     pWin->ppThis = &pSel->pWin;
1280   }
1281 }
1282 
1283 /*
1284 ** Return 0 if the two window objects are identical, 1 if they are
1285 ** different, or 2 if it cannot be determined if the objects are identical
1286 ** or not. Identical window objects can be processed in a single scan.
1287 */
1288 int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2, int bFilter){
1289   int res;
1290   if( NEVER(p1==0) || NEVER(p2==0) ) return 1;
1291   if( p1->eFrmType!=p2->eFrmType ) return 1;
1292   if( p1->eStart!=p2->eStart ) return 1;
1293   if( p1->eEnd!=p2->eEnd ) return 1;
1294   if( p1->eExclude!=p2->eExclude ) return 1;
1295   if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
1296   if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
1297   if( (res = sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1)) ){
1298     return res;
1299   }
1300   if( (res = sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1)) ){
1301     return res;
1302   }
1303   if( bFilter ){
1304     if( (res = sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1)) ){
1305       return res;
1306     }
1307   }
1308   return 0;
1309 }
1310 
1311 
1312 /*
1313 ** This is called by code in select.c before it calls sqlite3WhereBegin()
1314 ** to begin iterating through the sub-query results. It is used to allocate
1315 ** and initialize registers and cursors used by sqlite3WindowCodeStep().
1316 */
1317 void sqlite3WindowCodeInit(Parse *pParse, Select *pSelect){
1318   int nEphExpr = pSelect->pSrc->a[0].pSelect->pEList->nExpr;
1319   Window *pMWin = pSelect->pWin;
1320   Window *pWin;
1321   Vdbe *v = sqlite3GetVdbe(pParse);
1322 
1323   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr);
1324   sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
1325   sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
1326   sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
1327 
1328   /* Allocate registers to use for PARTITION BY values, if any. Initialize
1329   ** said registers to NULL.  */
1330   if( pMWin->pPartition ){
1331     int nExpr = pMWin->pPartition->nExpr;
1332     pMWin->regPart = pParse->nMem+1;
1333     pParse->nMem += nExpr;
1334     sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
1335   }
1336 
1337   pMWin->regOne = ++pParse->nMem;
1338   sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
1339 
1340   if( pMWin->eExclude ){
1341     pMWin->regStartRowid = ++pParse->nMem;
1342     pMWin->regEndRowid = ++pParse->nMem;
1343     pMWin->csrApp = pParse->nTab++;
1344     sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
1345     sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
1346     sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
1347     return;
1348   }
1349 
1350   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1351     FuncDef *p = pWin->pFunc;
1352     if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
1353       /* The inline versions of min() and max() require a single ephemeral
1354       ** table and 3 registers. The registers are used as follows:
1355       **
1356       **   regApp+0: slot to copy min()/max() argument to for MakeRecord
1357       **   regApp+1: integer value used to ensure keys are unique
1358       **   regApp+2: output of MakeRecord
1359       */
1360       ExprList *pList = pWin->pOwner->x.pList;
1361       KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
1362       pWin->csrApp = pParse->nTab++;
1363       pWin->regApp = pParse->nMem+1;
1364       pParse->nMem += 3;
1365       if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
1366         assert( pKeyInfo->aSortFlags[0]==0 );
1367         pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC;
1368       }
1369       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
1370       sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
1371       sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1372     }
1373     else if( p->zName==nth_valueName || p->zName==first_valueName ){
1374       /* Allocate two registers at pWin->regApp. These will be used to
1375       ** store the start and end index of the current frame.  */
1376       pWin->regApp = pParse->nMem+1;
1377       pWin->csrApp = pParse->nTab++;
1378       pParse->nMem += 2;
1379       sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1380     }
1381     else if( p->zName==leadName || p->zName==lagName ){
1382       pWin->csrApp = pParse->nTab++;
1383       sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1384     }
1385   }
1386 }
1387 
1388 #define WINDOW_STARTING_INT  0
1389 #define WINDOW_ENDING_INT    1
1390 #define WINDOW_NTH_VALUE_INT 2
1391 #define WINDOW_STARTING_NUM  3
1392 #define WINDOW_ENDING_NUM    4
1393 
1394 /*
1395 ** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
1396 ** value of the second argument to nth_value() (eCond==2) has just been
1397 ** evaluated and the result left in register reg. This function generates VM
1398 ** code to check that the value is a non-negative integer and throws an
1399 ** exception if it is not.
1400 */
1401 static void windowCheckValue(Parse *pParse, int reg, int eCond){
1402   static const char *azErr[] = {
1403     "frame starting offset must be a non-negative integer",
1404     "frame ending offset must be a non-negative integer",
1405     "second argument to nth_value must be a positive integer",
1406     "frame starting offset must be a non-negative number",
1407     "frame ending offset must be a non-negative number",
1408   };
1409   static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };
1410   Vdbe *v = sqlite3GetVdbe(pParse);
1411   int regZero = sqlite3GetTempReg(pParse);
1412   assert( eCond>=0 && eCond<ArraySize(azErr) );
1413   sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
1414   if( eCond>=WINDOW_STARTING_NUM ){
1415     int regString = sqlite3GetTempReg(pParse);
1416     sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
1417     sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);
1418     sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL);
1419     VdbeCoverage(v);
1420     assert( eCond==3 || eCond==4 );
1421     VdbeCoverageIf(v, eCond==3);
1422     VdbeCoverageIf(v, eCond==4);
1423   }else{
1424     sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
1425     VdbeCoverage(v);
1426     assert( eCond==0 || eCond==1 || eCond==2 );
1427     VdbeCoverageIf(v, eCond==0);
1428     VdbeCoverageIf(v, eCond==1);
1429     VdbeCoverageIf(v, eCond==2);
1430   }
1431   sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
1432   VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */
1433   VdbeCoverageNeverNullIf(v, eCond==1); /*   the OP_MustBeInt */
1434   VdbeCoverageNeverNullIf(v, eCond==2);
1435   VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */
1436   VdbeCoverageNeverNullIf(v, eCond==4); /*   the OP_Ge */
1437   sqlite3MayAbort(pParse);
1438   sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
1439   sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
1440   sqlite3ReleaseTempReg(pParse, regZero);
1441 }
1442 
1443 /*
1444 ** Return the number of arguments passed to the window-function associated
1445 ** with the object passed as the only argument to this function.
1446 */
1447 static int windowArgCount(Window *pWin){
1448   ExprList *pList = pWin->pOwner->x.pList;
1449   return (pList ? pList->nExpr : 0);
1450 }
1451 
1452 typedef struct WindowCodeArg WindowCodeArg;
1453 typedef struct WindowCsrAndReg WindowCsrAndReg;
1454 
1455 /*
1456 ** See comments above struct WindowCodeArg.
1457 */
1458 struct WindowCsrAndReg {
1459   int csr;                        /* Cursor number */
1460   int reg;                        /* First in array of peer values */
1461 };
1462 
1463 /*
1464 ** A single instance of this structure is allocated on the stack by
1465 ** sqlite3WindowCodeStep() and a pointer to it passed to the various helper
1466 ** routines. This is to reduce the number of arguments required by each
1467 ** helper function.
1468 **
1469 ** regArg:
1470 **   Each window function requires an accumulator register (just as an
1471 **   ordinary aggregate function does). This variable is set to the first
1472 **   in an array of accumulator registers - one for each window function
1473 **   in the WindowCodeArg.pMWin list.
1474 **
1475 ** eDelete:
1476 **   The window functions implementation sometimes caches the input rows
1477 **   that it processes in a temporary table. If it is not zero, this
1478 **   variable indicates when rows may be removed from the temp table (in
1479 **   order to reduce memory requirements - it would always be safe just
1480 **   to leave them there). Possible values for eDelete are:
1481 **
1482 **      WINDOW_RETURN_ROW:
1483 **        An input row can be discarded after it is returned to the caller.
1484 **
1485 **      WINDOW_AGGINVERSE:
1486 **        An input row can be discarded after the window functions xInverse()
1487 **        callbacks have been invoked in it.
1488 **
1489 **      WINDOW_AGGSTEP:
1490 **        An input row can be discarded after the window functions xStep()
1491 **        callbacks have been invoked in it.
1492 **
1493 ** start,current,end
1494 **   Consider a window-frame similar to the following:
1495 **
1496 **     (ORDER BY a, b GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING)
1497 **
1498 **   The windows functions implmentation caches the input rows in a temp
1499 **   table, sorted by "a, b" (it actually populates the cache lazily, and
1500 **   aggressively removes rows once they are no longer required, but that's
1501 **   a mere detail). It keeps three cursors open on the temp table. One
1502 **   (current) that points to the next row to return to the query engine
1503 **   once its window function values have been calculated. Another (end)
1504 **   points to the next row to call the xStep() method of each window function
1505 **   on (so that it is 2 groups ahead of current). And a third (start) that
1506 **   points to the next row to call the xInverse() method of each window
1507 **   function on.
1508 **
1509 **   Each cursor (start, current and end) consists of a VDBE cursor
1510 **   (WindowCsrAndReg.csr) and an array of registers (starting at
1511 **   WindowCodeArg.reg) that always contains a copy of the peer values
1512 **   read from the corresponding cursor.
1513 **
1514 **   Depending on the window-frame in question, all three cursors may not
1515 **   be required. In this case both WindowCodeArg.csr and reg are set to
1516 **   0.
1517 */
1518 struct WindowCodeArg {
1519   Parse *pParse;             /* Parse context */
1520   Window *pMWin;             /* First in list of functions being processed */
1521   Vdbe *pVdbe;               /* VDBE object */
1522   int addrGosub;             /* OP_Gosub to this address to return one row */
1523   int regGosub;              /* Register used with OP_Gosub(addrGosub) */
1524   int regArg;                /* First in array of accumulator registers */
1525   int eDelete;               /* See above */
1526 
1527   WindowCsrAndReg start;
1528   WindowCsrAndReg current;
1529   WindowCsrAndReg end;
1530 };
1531 
1532 /*
1533 ** Generate VM code to read the window frames peer values from cursor csr into
1534 ** an array of registers starting at reg.
1535 */
1536 static void windowReadPeerValues(
1537   WindowCodeArg *p,
1538   int csr,
1539   int reg
1540 ){
1541   Window *pMWin = p->pMWin;
1542   ExprList *pOrderBy = pMWin->pOrderBy;
1543   if( pOrderBy ){
1544     Vdbe *v = sqlite3GetVdbe(p->pParse);
1545     ExprList *pPart = pMWin->pPartition;
1546     int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
1547     int i;
1548     for(i=0; i<pOrderBy->nExpr; i++){
1549       sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
1550     }
1551   }
1552 }
1553 
1554 /*
1555 ** Generate VM code to invoke either xStep() (if bInverse is 0) or
1556 ** xInverse (if bInverse is non-zero) for each window function in the
1557 ** linked list starting at pMWin. Or, for built-in window functions
1558 ** that do not use the standard function API, generate the required
1559 ** inline VM code.
1560 **
1561 ** If argument csr is greater than or equal to 0, then argument reg is
1562 ** the first register in an array of registers guaranteed to be large
1563 ** enough to hold the array of arguments for each function. In this case
1564 ** the arguments are extracted from the current row of csr into the
1565 ** array of registers before invoking OP_AggStep or OP_AggInverse
1566 **
1567 ** Or, if csr is less than zero, then the array of registers at reg is
1568 ** already populated with all columns from the current row of the sub-query.
1569 **
1570 ** If argument regPartSize is non-zero, then it is a register containing the
1571 ** number of rows in the current partition.
1572 */
1573 static void windowAggStep(
1574   WindowCodeArg *p,
1575   Window *pMWin,                  /* Linked list of window functions */
1576   int csr,                        /* Read arguments from this cursor */
1577   int bInverse,                   /* True to invoke xInverse instead of xStep */
1578   int reg                         /* Array of registers */
1579 ){
1580   Parse *pParse = p->pParse;
1581   Vdbe *v = sqlite3GetVdbe(pParse);
1582   Window *pWin;
1583   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1584     FuncDef *pFunc = pWin->pFunc;
1585     int regArg;
1586     int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin);
1587     int i;
1588 
1589     assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED );
1590 
1591     /* All OVER clauses in the same window function aggregate step must
1592     ** be the same. */
1593     assert( pWin==pMWin || sqlite3WindowCompare(pParse,pWin,pMWin,0)!=1 );
1594 
1595     for(i=0; i<nArg; i++){
1596       if( i!=1 || pFunc->zName!=nth_valueName ){
1597         sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
1598       }else{
1599         sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
1600       }
1601     }
1602     regArg = reg;
1603 
1604     if( pMWin->regStartRowid==0
1605      && (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1606      && (pWin->eStart!=TK_UNBOUNDED)
1607     ){
1608       int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
1609       VdbeCoverage(v);
1610       if( bInverse==0 ){
1611         sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
1612         sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
1613         sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
1614         sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
1615       }else{
1616         sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
1617         VdbeCoverageNeverTaken(v);
1618         sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
1619         sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1620       }
1621       sqlite3VdbeJumpHere(v, addrIsNull);
1622     }else if( pWin->regApp ){
1623       assert( pFunc->zName==nth_valueName
1624            || pFunc->zName==first_valueName
1625       );
1626       assert( bInverse==0 || bInverse==1 );
1627       sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
1628     }else if( pFunc->xSFunc!=noopStepFunc ){
1629       int addrIf = 0;
1630       if( pWin->pFilter ){
1631         int regTmp;
1632         assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr );
1633         assert( pWin->bExprArgs || nArg  ||pWin->pOwner->x.pList==0 );
1634         regTmp = sqlite3GetTempReg(pParse);
1635         sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
1636         addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
1637         VdbeCoverage(v);
1638         sqlite3ReleaseTempReg(pParse, regTmp);
1639       }
1640 
1641       if( pWin->bExprArgs ){
1642         int iStart = sqlite3VdbeCurrentAddr(v);
1643         VdbeOp *pOp, *pEnd;
1644 
1645         nArg = pWin->pOwner->x.pList->nExpr;
1646         regArg = sqlite3GetTempRange(pParse, nArg);
1647         sqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0);
1648 
1649         pEnd = sqlite3VdbeGetOp(v, -1);
1650         for(pOp=sqlite3VdbeGetOp(v, iStart); pOp<=pEnd; pOp++){
1651           if( pOp->opcode==OP_Column && pOp->p1==pWin->iEphCsr ){
1652             pOp->p1 = csr;
1653           }
1654         }
1655       }
1656       if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
1657         CollSeq *pColl;
1658         assert( nArg>0 );
1659         pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
1660         sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
1661       }
1662       sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
1663                         bInverse, regArg, pWin->regAccum);
1664       sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
1665       sqlite3VdbeChangeP5(v, (u8)nArg);
1666       if( pWin->bExprArgs ){
1667         sqlite3ReleaseTempRange(pParse, regArg, nArg);
1668       }
1669       if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
1670     }
1671   }
1672 }
1673 
1674 /*
1675 ** Values that may be passed as the second argument to windowCodeOp().
1676 */
1677 #define WINDOW_RETURN_ROW 1
1678 #define WINDOW_AGGINVERSE 2
1679 #define WINDOW_AGGSTEP    3
1680 
1681 /*
1682 ** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
1683 ** (bFin==1) for each window function in the linked list starting at
1684 ** pMWin. Or, for built-in window-functions that do not use the standard
1685 ** API, generate the equivalent VM code.
1686 */
1687 static void windowAggFinal(WindowCodeArg *p, int bFin){
1688   Parse *pParse = p->pParse;
1689   Window *pMWin = p->pMWin;
1690   Vdbe *v = sqlite3GetVdbe(pParse);
1691   Window *pWin;
1692 
1693   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1694     if( pMWin->regStartRowid==0
1695      && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1696      && (pWin->eStart!=TK_UNBOUNDED)
1697     ){
1698       sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1699       sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
1700       VdbeCoverage(v);
1701       sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
1702       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1703     }else if( pWin->regApp ){
1704       assert( pMWin->regStartRowid==0 );
1705     }else{
1706       int nArg = windowArgCount(pWin);
1707       if( bFin ){
1708         sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
1709         sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
1710         sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
1711         sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1712       }else{
1713         sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
1714         sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
1715       }
1716     }
1717   }
1718 }
1719 
1720 /*
1721 ** Generate code to calculate the current values of all window functions in the
1722 ** p->pMWin list by doing a full scan of the current window frame. Store the
1723 ** results in the Window.regResult registers, ready to return the upper
1724 ** layer.
1725 */
1726 static void windowFullScan(WindowCodeArg *p){
1727   Window *pWin;
1728   Parse *pParse = p->pParse;
1729   Window *pMWin = p->pMWin;
1730   Vdbe *v = p->pVdbe;
1731 
1732   int regCRowid = 0;              /* Current rowid value */
1733   int regCPeer = 0;               /* Current peer values */
1734   int regRowid = 0;               /* AggStep rowid value */
1735   int regPeer = 0;                /* AggStep peer values */
1736 
1737   int nPeer;
1738   int lblNext;
1739   int lblBrk;
1740   int addrNext;
1741   int csr;
1742 
1743   VdbeModuleComment((v, "windowFullScan begin"));
1744 
1745   assert( pMWin!=0 );
1746   csr = pMWin->csrApp;
1747   nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
1748 
1749   lblNext = sqlite3VdbeMakeLabel(pParse);
1750   lblBrk = sqlite3VdbeMakeLabel(pParse);
1751 
1752   regCRowid = sqlite3GetTempReg(pParse);
1753   regRowid = sqlite3GetTempReg(pParse);
1754   if( nPeer ){
1755     regCPeer = sqlite3GetTempRange(pParse, nPeer);
1756     regPeer = sqlite3GetTempRange(pParse, nPeer);
1757   }
1758 
1759   sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
1760   windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
1761 
1762   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1763     sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1764   }
1765 
1766   sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
1767   VdbeCoverage(v);
1768   addrNext = sqlite3VdbeCurrentAddr(v);
1769   sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);
1770   sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
1771   VdbeCoverageNeverNull(v);
1772 
1773   if( pMWin->eExclude==TK_CURRENT ){
1774     sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);
1775     VdbeCoverageNeverNull(v);
1776   }else if( pMWin->eExclude!=TK_NO ){
1777     int addr;
1778     int addrEq = 0;
1779     KeyInfo *pKeyInfo = 0;
1780 
1781     if( pMWin->pOrderBy ){
1782       pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
1783     }
1784     if( pMWin->eExclude==TK_TIES ){
1785       addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);
1786       VdbeCoverageNeverNull(v);
1787     }
1788     if( pKeyInfo ){
1789       windowReadPeerValues(p, csr, regPeer);
1790       sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);
1791       sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1792       addr = sqlite3VdbeCurrentAddr(v)+1;
1793       sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);
1794       VdbeCoverageEqNe(v);
1795     }else{
1796       sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);
1797     }
1798     if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);
1799   }
1800 
1801   windowAggStep(p, pMWin, csr, 0, p->regArg);
1802 
1803   sqlite3VdbeResolveLabel(v, lblNext);
1804   sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);
1805   VdbeCoverage(v);
1806   sqlite3VdbeJumpHere(v, addrNext-1);
1807   sqlite3VdbeJumpHere(v, addrNext+1);
1808   sqlite3ReleaseTempReg(pParse, regRowid);
1809   sqlite3ReleaseTempReg(pParse, regCRowid);
1810   if( nPeer ){
1811     sqlite3ReleaseTempRange(pParse, regPeer, nPeer);
1812     sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);
1813   }
1814 
1815   windowAggFinal(p, 1);
1816   VdbeModuleComment((v, "windowFullScan end"));
1817 }
1818 
1819 /*
1820 ** Invoke the sub-routine at regGosub (generated by code in select.c) to
1821 ** return the current row of Window.iEphCsr. If all window functions are
1822 ** aggregate window functions that use the standard API, a single
1823 ** OP_Gosub instruction is all that this routine generates. Extra VM code
1824 ** for per-row processing is only generated for the following built-in window
1825 ** functions:
1826 **
1827 **   nth_value()
1828 **   first_value()
1829 **   lag()
1830 **   lead()
1831 */
1832 static void windowReturnOneRow(WindowCodeArg *p){
1833   Window *pMWin = p->pMWin;
1834   Vdbe *v = p->pVdbe;
1835 
1836   if( pMWin->regStartRowid ){
1837     windowFullScan(p);
1838   }else{
1839     Parse *pParse = p->pParse;
1840     Window *pWin;
1841 
1842     for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1843       FuncDef *pFunc = pWin->pFunc;
1844       if( pFunc->zName==nth_valueName
1845        || pFunc->zName==first_valueName
1846       ){
1847         int csr = pWin->csrApp;
1848         int lbl = sqlite3VdbeMakeLabel(pParse);
1849         int tmpReg = sqlite3GetTempReg(pParse);
1850         sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1851 
1852         if( pFunc->zName==nth_valueName ){
1853           sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
1854           windowCheckValue(pParse, tmpReg, 2);
1855         }else{
1856           sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
1857         }
1858         sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
1859         sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
1860         VdbeCoverageNeverNull(v);
1861         sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
1862         VdbeCoverageNeverTaken(v);
1863         sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1864         sqlite3VdbeResolveLabel(v, lbl);
1865         sqlite3ReleaseTempReg(pParse, tmpReg);
1866       }
1867       else if( pFunc->zName==leadName || pFunc->zName==lagName ){
1868         int nArg = pWin->pOwner->x.pList->nExpr;
1869         int csr = pWin->csrApp;
1870         int lbl = sqlite3VdbeMakeLabel(pParse);
1871         int tmpReg = sqlite3GetTempReg(pParse);
1872         int iEph = pMWin->iEphCsr;
1873 
1874         if( nArg<3 ){
1875           sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1876         }else{
1877           sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
1878         }
1879         sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
1880         if( nArg<2 ){
1881           int val = (pFunc->zName==leadName ? 1 : -1);
1882           sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
1883         }else{
1884           int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
1885           int tmpReg2 = sqlite3GetTempReg(pParse);
1886           sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
1887           sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
1888           sqlite3ReleaseTempReg(pParse, tmpReg2);
1889         }
1890 
1891         sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
1892         VdbeCoverage(v);
1893         sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1894         sqlite3VdbeResolveLabel(v, lbl);
1895         sqlite3ReleaseTempReg(pParse, tmpReg);
1896       }
1897     }
1898   }
1899   sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
1900 }
1901 
1902 /*
1903 ** Generate code to set the accumulator register for each window function
1904 ** in the linked list passed as the second argument to NULL. And perform
1905 ** any equivalent initialization required by any built-in window functions
1906 ** in the list.
1907 */
1908 static int windowInitAccum(Parse *pParse, Window *pMWin){
1909   Vdbe *v = sqlite3GetVdbe(pParse);
1910   int regArg;
1911   int nArg = 0;
1912   Window *pWin;
1913   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1914     FuncDef *pFunc = pWin->pFunc;
1915     assert( pWin->regAccum );
1916     sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1917     nArg = MAX(nArg, windowArgCount(pWin));
1918     if( pMWin->regStartRowid==0 ){
1919       if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
1920         sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
1921         sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1922       }
1923 
1924       if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
1925         assert( pWin->eStart!=TK_UNBOUNDED );
1926         sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
1927         sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1928       }
1929     }
1930   }
1931   regArg = pParse->nMem+1;
1932   pParse->nMem += nArg;
1933   return regArg;
1934 }
1935 
1936 /*
1937 ** Return true if the current frame should be cached in the ephemeral table,
1938 ** even if there are no xInverse() calls required.
1939 */
1940 static int windowCacheFrame(Window *pMWin){
1941   Window *pWin;
1942   if( pMWin->regStartRowid ) return 1;
1943   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1944     FuncDef *pFunc = pWin->pFunc;
1945     if( (pFunc->zName==nth_valueName)
1946      || (pFunc->zName==first_valueName)
1947      || (pFunc->zName==leadName)
1948      || (pFunc->zName==lagName)
1949     ){
1950       return 1;
1951     }
1952   }
1953   return 0;
1954 }
1955 
1956 /*
1957 ** regOld and regNew are each the first register in an array of size
1958 ** pOrderBy->nExpr. This function generates code to compare the two
1959 ** arrays of registers using the collation sequences and other comparison
1960 ** parameters specified by pOrderBy.
1961 **
1962 ** If the two arrays are not equal, the contents of regNew is copied to
1963 ** regOld and control falls through. Otherwise, if the contents of the arrays
1964 ** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
1965 */
1966 static void windowIfNewPeer(
1967   Parse *pParse,
1968   ExprList *pOrderBy,
1969   int regNew,                     /* First in array of new values */
1970   int regOld,                     /* First in array of old values */
1971   int addr                        /* Jump here */
1972 ){
1973   Vdbe *v = sqlite3GetVdbe(pParse);
1974   if( pOrderBy ){
1975     int nVal = pOrderBy->nExpr;
1976     KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
1977     sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
1978     sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1979     sqlite3VdbeAddOp3(v, OP_Jump,
1980       sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
1981     );
1982     VdbeCoverageEqNe(v);
1983     sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
1984   }else{
1985     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
1986   }
1987 }
1988 
1989 /*
1990 ** This function is called as part of generating VM programs for RANGE
1991 ** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
1992 ** the ORDER BY term in the window, and that argument op is OP_Ge, it generates
1993 ** code equivalent to:
1994 **
1995 **   if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
1996 **
1997 ** The value of parameter op may also be OP_Gt or OP_Le. In these cases the
1998 ** operator in the above pseudo-code is replaced with ">" or "<=", respectively.
1999 **
2000 ** If the sort-order for the ORDER BY term in the window is DESC, then the
2001 ** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is
2002 ** subtracted. And the comparison operator is inverted to - ">=" becomes "<=",
2003 ** ">" becomes "<", and so on. So, with DESC sort order, if the argument op
2004 ** is OP_Ge, the generated code is equivalent to:
2005 **
2006 **   if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;
2007 **
2008 ** A special type of arithmetic is used such that if csr1.peerVal is not
2009 ** a numeric type (real or integer), then the result of the addition addition
2010 ** or subtraction is a a copy of csr1.peerVal.
2011 */
2012 static void windowCodeRangeTest(
2013   WindowCodeArg *p,
2014   int op,                         /* OP_Ge, OP_Gt, or OP_Le */
2015   int csr1,                       /* Cursor number for cursor 1 */
2016   int regVal,                     /* Register containing non-negative number */
2017   int csr2,                       /* Cursor number for cursor 2 */
2018   int lbl                         /* Jump destination if condition is true */
2019 ){
2020   Parse *pParse = p->pParse;
2021   Vdbe *v = sqlite3GetVdbe(pParse);
2022   ExprList *pOrderBy = p->pMWin->pOrderBy;  /* ORDER BY clause for window */
2023   int reg1 = sqlite3GetTempReg(pParse);     /* Reg. for csr1.peerVal+regVal */
2024   int reg2 = sqlite3GetTempReg(pParse);     /* Reg. for csr2.peerVal */
2025   int regString = ++pParse->nMem;           /* Reg. for constant value '' */
2026   int arith = OP_Add;                       /* OP_Add or OP_Subtract */
2027   int addrGe;                               /* Jump destination */
2028 
2029   assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
2030   assert( pOrderBy && pOrderBy->nExpr==1 );
2031   if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_DESC ){
2032     switch( op ){
2033       case OP_Ge: op = OP_Le; break;
2034       case OP_Gt: op = OP_Lt; break;
2035       default: assert( op==OP_Le ); op = OP_Ge; break;
2036     }
2037     arith = OP_Subtract;
2038   }
2039 
2040   /* Read the peer-value from each cursor into a register */
2041   windowReadPeerValues(p, csr1, reg1);
2042   windowReadPeerValues(p, csr2, reg2);
2043 
2044   VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl",
2045       reg1, (arith==OP_Add ? "+" : "-"), regVal,
2046       ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2
2047   ));
2048 
2049   /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).
2050   ** This block adds (or subtracts for DESC) the numeric value in regVal
2051   ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob),
2052   ** then leave reg1 as it is. In pseudo-code, this is implemented as:
2053   **
2054   **   if( reg1>='' ) goto addrGe;
2055   **   reg1 = reg1 +/- regVal
2056   **   addrGe:
2057   **
2058   ** Since all strings and blobs are greater-than-or-equal-to an empty string,
2059   ** the add/subtract is skipped for these, as required. If reg1 is a NULL,
2060   ** then the arithmetic is performed, but since adding or subtracting from
2061   ** NULL is always NULL anyway, this case is handled as required too.  */
2062   sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
2063   addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
2064   VdbeCoverage(v);
2065   sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
2066   sqlite3VdbeJumpHere(v, addrGe);
2067 
2068   /* If the BIGNULL flag is set for the ORDER BY, then it is required to
2069   ** consider NULL values to be larger than all other values, instead of
2070   ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this
2071   ** (and adding that capability causes a performance regression), so
2072   ** instead if the BIGNULL flag is set then cases where either reg1 or
2073   ** reg2 are NULL are handled separately in the following block. The code
2074   ** generated is equivalent to:
2075   **
2076   **   if( reg1 IS NULL ){
2077   **     if( op==OP_Ge ) goto lbl;
2078   **     if( op==OP_Gt && reg2 IS NOT NULL ) goto lbl;
2079   **     if( op==OP_Le && reg2 IS NULL ) goto lbl;
2080   **   }else if( reg2 IS NULL ){
2081   **     if( op==OP_Le ) goto lbl;
2082   **   }
2083   **
2084   ** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is
2085   ** not taken, control jumps over the comparison operator coded below this
2086   ** block.  */
2087   if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_BIGNULL ){
2088     /* This block runs if reg1 contains a NULL. */
2089     int addr = sqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v);
2090     switch( op ){
2091       case OP_Ge:
2092         sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl);
2093         break;
2094       case OP_Gt:
2095         sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl);
2096         VdbeCoverage(v);
2097         break;
2098       case OP_Le:
2099         sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl);
2100         VdbeCoverage(v);
2101         break;
2102       default: assert( op==OP_Lt ); /* no-op */ break;
2103     }
2104     sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
2105 
2106     /* This block runs if reg1 is not NULL, but reg2 is. */
2107     sqlite3VdbeJumpHere(v, addr);
2108     sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); VdbeCoverage(v);
2109     if( op==OP_Gt || op==OP_Ge ){
2110       sqlite3VdbeChangeP2(v, -1, sqlite3VdbeCurrentAddr(v)+1);
2111     }
2112   }
2113 
2114   /* Compare registers reg2 and reg1, taking the jump if required. Note that
2115   ** control skips over this test if the BIGNULL flag is set and either
2116   ** reg1 or reg2 contain a NULL value.  */
2117   sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
2118   sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
2119 
2120   assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
2121   testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);
2122   testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt);
2123   testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le);
2124   testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt);
2125   sqlite3ReleaseTempReg(pParse, reg1);
2126   sqlite3ReleaseTempReg(pParse, reg2);
2127 
2128   VdbeModuleComment((v, "CodeRangeTest: end"));
2129 }
2130 
2131 /*
2132 ** Helper function for sqlite3WindowCodeStep(). Each call to this function
2133 ** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
2134 ** operation. Refer to the header comment for sqlite3WindowCodeStep() for
2135 ** details.
2136 */
2137 static int windowCodeOp(
2138  WindowCodeArg *p,                /* Context object */
2139  int op,                          /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
2140  int regCountdown,                /* Register for OP_IfPos countdown */
2141  int jumpOnEof                    /* Jump here if stepped cursor reaches EOF */
2142 ){
2143   int csr, reg;
2144   Parse *pParse = p->pParse;
2145   Window *pMWin = p->pMWin;
2146   int ret = 0;
2147   Vdbe *v = p->pVdbe;
2148   int addrContinue = 0;
2149   int bPeer = (pMWin->eFrmType!=TK_ROWS);
2150 
2151   int lblDone = sqlite3VdbeMakeLabel(pParse);
2152   int addrNextRange = 0;
2153 
2154   /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
2155   ** starts with UNBOUNDED PRECEDING. */
2156   if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
2157     assert( regCountdown==0 && jumpOnEof==0 );
2158     return 0;
2159   }
2160 
2161   if( regCountdown>0 ){
2162     if( pMWin->eFrmType==TK_RANGE ){
2163       addrNextRange = sqlite3VdbeCurrentAddr(v);
2164       assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );
2165       if( op==WINDOW_AGGINVERSE ){
2166         if( pMWin->eStart==TK_FOLLOWING ){
2167           windowCodeRangeTest(
2168               p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
2169           );
2170         }else{
2171           windowCodeRangeTest(
2172               p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
2173           );
2174         }
2175       }else{
2176         windowCodeRangeTest(
2177             p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
2178         );
2179       }
2180     }else{
2181       sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, lblDone, 1);
2182       VdbeCoverage(v);
2183     }
2184   }
2185 
2186   if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
2187     windowAggFinal(p, 0);
2188   }
2189   addrContinue = sqlite3VdbeCurrentAddr(v);
2190 
2191   /* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or
2192   ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the
2193   ** start cursor does not advance past the end cursor within the
2194   ** temporary table. It otherwise might, if (a>b).  */
2195   if( pMWin->eStart==pMWin->eEnd && regCountdown
2196    && pMWin->eFrmType==TK_RANGE && op==WINDOW_AGGINVERSE
2197   ){
2198     int regRowid1 = sqlite3GetTempReg(pParse);
2199     int regRowid2 = sqlite3GetTempReg(pParse);
2200     sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1);
2201     sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2);
2202     sqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1);
2203     VdbeCoverage(v);
2204     sqlite3ReleaseTempReg(pParse, regRowid1);
2205     sqlite3ReleaseTempReg(pParse, regRowid2);
2206     assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING );
2207   }
2208 
2209   switch( op ){
2210     case WINDOW_RETURN_ROW:
2211       csr = p->current.csr;
2212       reg = p->current.reg;
2213       windowReturnOneRow(p);
2214       break;
2215 
2216     case WINDOW_AGGINVERSE:
2217       csr = p->start.csr;
2218       reg = p->start.reg;
2219       if( pMWin->regStartRowid ){
2220         assert( pMWin->regEndRowid );
2221         sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
2222       }else{
2223         windowAggStep(p, pMWin, csr, 1, p->regArg);
2224       }
2225       break;
2226 
2227     default:
2228       assert( op==WINDOW_AGGSTEP );
2229       csr = p->end.csr;
2230       reg = p->end.reg;
2231       if( pMWin->regStartRowid ){
2232         assert( pMWin->regEndRowid );
2233         sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
2234       }else{
2235         windowAggStep(p, pMWin, csr, 0, p->regArg);
2236       }
2237       break;
2238   }
2239 
2240   if( op==p->eDelete ){
2241     sqlite3VdbeAddOp1(v, OP_Delete, csr);
2242     sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
2243   }
2244 
2245   if( jumpOnEof ){
2246     sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
2247     VdbeCoverage(v);
2248     ret = sqlite3VdbeAddOp0(v, OP_Goto);
2249   }else{
2250     sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
2251     VdbeCoverage(v);
2252     if( bPeer ){
2253       sqlite3VdbeAddOp2(v, OP_Goto, 0, lblDone);
2254     }
2255   }
2256 
2257   if( bPeer ){
2258     int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
2259     int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
2260     windowReadPeerValues(p, csr, regTmp);
2261     windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
2262     sqlite3ReleaseTempRange(pParse, regTmp, nReg);
2263   }
2264 
2265   if( addrNextRange ){
2266     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
2267   }
2268   sqlite3VdbeResolveLabel(v, lblDone);
2269   return ret;
2270 }
2271 
2272 
2273 /*
2274 ** Allocate and return a duplicate of the Window object indicated by the
2275 ** third argument. Set the Window.pOwner field of the new object to
2276 ** pOwner.
2277 */
2278 Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
2279   Window *pNew = 0;
2280   if( ALWAYS(p) ){
2281     pNew = sqlite3DbMallocZero(db, sizeof(Window));
2282     if( pNew ){
2283       pNew->zName = sqlite3DbStrDup(db, p->zName);
2284       pNew->zBase = sqlite3DbStrDup(db, p->zBase);
2285       pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
2286       pNew->pFunc = p->pFunc;
2287       pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
2288       pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
2289       pNew->eFrmType = p->eFrmType;
2290       pNew->eEnd = p->eEnd;
2291       pNew->eStart = p->eStart;
2292       pNew->eExclude = p->eExclude;
2293       pNew->regResult = p->regResult;
2294       pNew->regAccum = p->regAccum;
2295       pNew->iArgCol = p->iArgCol;
2296       pNew->iEphCsr = p->iEphCsr;
2297       pNew->bExprArgs = p->bExprArgs;
2298       pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
2299       pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
2300       pNew->pOwner = pOwner;
2301       pNew->bImplicitFrame = p->bImplicitFrame;
2302     }
2303   }
2304   return pNew;
2305 }
2306 
2307 /*
2308 ** Return a copy of the linked list of Window objects passed as the
2309 ** second argument.
2310 */
2311 Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
2312   Window *pWin;
2313   Window *pRet = 0;
2314   Window **pp = &pRet;
2315 
2316   for(pWin=p; pWin; pWin=pWin->pNextWin){
2317     *pp = sqlite3WindowDup(db, 0, pWin);
2318     if( *pp==0 ) break;
2319     pp = &((*pp)->pNextWin);
2320   }
2321 
2322   return pRet;
2323 }
2324 
2325 /*
2326 ** Return true if it can be determined at compile time that expression
2327 ** pExpr evaluates to a value that, when cast to an integer, is greater
2328 ** than zero. False otherwise.
2329 **
2330 ** If an OOM error occurs, this function sets the Parse.db.mallocFailed
2331 ** flag and returns zero.
2332 */
2333 static int windowExprGtZero(Parse *pParse, Expr *pExpr){
2334   int ret = 0;
2335   sqlite3 *db = pParse->db;
2336   sqlite3_value *pVal = 0;
2337   sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);
2338   if( pVal && sqlite3_value_int(pVal)>0 ){
2339     ret = 1;
2340   }
2341   sqlite3ValueFree(pVal);
2342   return ret;
2343 }
2344 
2345 /*
2346 ** sqlite3WhereBegin() has already been called for the SELECT statement
2347 ** passed as the second argument when this function is invoked. It generates
2348 ** code to populate the Window.regResult register for each window function
2349 ** and invoke the sub-routine at instruction addrGosub once for each row.
2350 ** sqlite3WhereEnd() is always called before returning.
2351 **
2352 ** This function handles several different types of window frames, which
2353 ** require slightly different processing. The following pseudo code is
2354 ** used to implement window frames of the form:
2355 **
2356 **   ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
2357 **
2358 ** Other window frame types use variants of the following:
2359 **
2360 **     ... loop started by sqlite3WhereBegin() ...
2361 **       if( new partition ){
2362 **         Gosub flush
2363 **       }
2364 **       Insert new row into eph table.
2365 **
2366 **       if( first row of partition ){
2367 **         // Rewind three cursors, all open on the eph table.
2368 **         Rewind(csrEnd);
2369 **         Rewind(csrStart);
2370 **         Rewind(csrCurrent);
2371 **
2372 **         regEnd = <expr2>          // FOLLOWING expression
2373 **         regStart = <expr1>        // PRECEDING expression
2374 **       }else{
2375 **         // First time this branch is taken, the eph table contains two
2376 **         // rows. The first row in the partition, which all three cursors
2377 **         // currently point to, and the following row.
2378 **         AGGSTEP
2379 **         if( (regEnd--)<=0 ){
2380 **           RETURN_ROW
2381 **           if( (regStart--)<=0 ){
2382 **             AGGINVERSE
2383 **           }
2384 **         }
2385 **       }
2386 **     }
2387 **     flush:
2388 **       AGGSTEP
2389 **       while( 1 ){
2390 **         RETURN ROW
2391 **         if( csrCurrent is EOF ) break;
2392 **         if( (regStart--)<=0 ){
2393 **           AggInverse(csrStart)
2394 **           Next(csrStart)
2395 **         }
2396 **       }
2397 **
2398 ** The pseudo-code above uses the following shorthand:
2399 **
2400 **   AGGSTEP:    invoke the aggregate xStep() function for each window function
2401 **               with arguments read from the current row of cursor csrEnd, then
2402 **               step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
2403 **
2404 **   RETURN_ROW: return a row to the caller based on the contents of the
2405 **               current row of csrCurrent and the current state of all
2406 **               aggregates. Then step cursor csrCurrent forward one row.
2407 **
2408 **   AGGINVERSE: invoke the aggregate xInverse() function for each window
2409 **               functions with arguments read from the current row of cursor
2410 **               csrStart. Then step csrStart forward one row.
2411 **
2412 ** There are two other ROWS window frames that are handled significantly
2413 ** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
2414 ** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
2415 ** cases because they change the order in which the three cursors (csrStart,
2416 ** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
2417 ** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
2418 ** three.
2419 **
2420 **   ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2421 **
2422 **     ... loop started by sqlite3WhereBegin() ...
2423 **       if( new partition ){
2424 **         Gosub flush
2425 **       }
2426 **       Insert new row into eph table.
2427 **       if( first row of partition ){
2428 **         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2429 **         regEnd = <expr2>
2430 **         regStart = <expr1>
2431 **       }else{
2432 **         if( (regEnd--)<=0 ){
2433 **           AGGSTEP
2434 **         }
2435 **         RETURN_ROW
2436 **         if( (regStart--)<=0 ){
2437 **           AGGINVERSE
2438 **         }
2439 **       }
2440 **     }
2441 **     flush:
2442 **       if( (regEnd--)<=0 ){
2443 **         AGGSTEP
2444 **       }
2445 **       RETURN_ROW
2446 **
2447 **
2448 **   ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2449 **
2450 **     ... loop started by sqlite3WhereBegin() ...
2451 **     if( new partition ){
2452 **       Gosub flush
2453 **     }
2454 **     Insert new row into eph table.
2455 **     if( first row of partition ){
2456 **       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2457 **       regEnd = <expr2>
2458 **       regStart = regEnd - <expr1>
2459 **     }else{
2460 **       AGGSTEP
2461 **       if( (regEnd--)<=0 ){
2462 **         RETURN_ROW
2463 **       }
2464 **       if( (regStart--)<=0 ){
2465 **         AGGINVERSE
2466 **       }
2467 **     }
2468 **   }
2469 **   flush:
2470 **     AGGSTEP
2471 **     while( 1 ){
2472 **       if( (regEnd--)<=0 ){
2473 **         RETURN_ROW
2474 **         if( eof ) break;
2475 **       }
2476 **       if( (regStart--)<=0 ){
2477 **         AGGINVERSE
2478 **         if( eof ) break
2479 **       }
2480 **     }
2481 **     while( !eof csrCurrent ){
2482 **       RETURN_ROW
2483 **     }
2484 **
2485 ** For the most part, the patterns above are adapted to support UNBOUNDED by
2486 ** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
2487 ** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING".
2488 ** This is optimized of course - branches that will never be taken and
2489 ** conditions that are always true are omitted from the VM code. The only
2490 ** exceptional case is:
2491 **
2492 **   ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
2493 **
2494 **     ... loop started by sqlite3WhereBegin() ...
2495 **     if( new partition ){
2496 **       Gosub flush
2497 **     }
2498 **     Insert new row into eph table.
2499 **     if( first row of partition ){
2500 **       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2501 **       regStart = <expr1>
2502 **     }else{
2503 **       AGGSTEP
2504 **     }
2505 **   }
2506 **   flush:
2507 **     AGGSTEP
2508 **     while( 1 ){
2509 **       if( (regStart--)<=0 ){
2510 **         AGGINVERSE
2511 **         if( eof ) break
2512 **       }
2513 **       RETURN_ROW
2514 **     }
2515 **     while( !eof csrCurrent ){
2516 **       RETURN_ROW
2517 **     }
2518 **
2519 ** Also requiring special handling are the cases:
2520 **
2521 **   ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2522 **   ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2523 **
2524 ** when (expr1 < expr2). This is detected at runtime, not by this function.
2525 ** To handle this case, the pseudo-code programs depicted above are modified
2526 ** slightly to be:
2527 **
2528 **     ... loop started by sqlite3WhereBegin() ...
2529 **     if( new partition ){
2530 **       Gosub flush
2531 **     }
2532 **     Insert new row into eph table.
2533 **     if( first row of partition ){
2534 **       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2535 **       regEnd = <expr2>
2536 **       regStart = <expr1>
2537 **       if( regEnd < regStart ){
2538 **         RETURN_ROW
2539 **         delete eph table contents
2540 **         continue
2541 **       }
2542 **     ...
2543 **
2544 ** The new "continue" statement in the above jumps to the next iteration
2545 ** of the outer loop - the one started by sqlite3WhereBegin().
2546 **
2547 ** The various GROUPS cases are implemented using the same patterns as
2548 ** ROWS. The VM code is modified slightly so that:
2549 **
2550 **   1. The else branch in the main loop is only taken if the row just
2551 **      added to the ephemeral table is the start of a new group. In
2552 **      other words, it becomes:
2553 **
2554 **         ... loop started by sqlite3WhereBegin() ...
2555 **         if( new partition ){
2556 **           Gosub flush
2557 **         }
2558 **         Insert new row into eph table.
2559 **         if( first row of partition ){
2560 **           Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2561 **           regEnd = <expr2>
2562 **           regStart = <expr1>
2563 **         }else if( new group ){
2564 **           ...
2565 **         }
2566 **       }
2567 **
2568 **   2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
2569 **      AGGINVERSE step processes the current row of the relevant cursor and
2570 **      all subsequent rows belonging to the same group.
2571 **
2572 ** RANGE window frames are a little different again. As for GROUPS, the
2573 ** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
2574 ** deal in groups instead of rows. As for ROWS and GROUPS, there are three
2575 ** basic cases:
2576 **
2577 **   RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
2578 **
2579 **     ... loop started by sqlite3WhereBegin() ...
2580 **       if( new partition ){
2581 **         Gosub flush
2582 **       }
2583 **       Insert new row into eph table.
2584 **       if( first row of partition ){
2585 **         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2586 **         regEnd = <expr2>
2587 **         regStart = <expr1>
2588 **       }else{
2589 **         AGGSTEP
2590 **         while( (csrCurrent.key + regEnd) < csrEnd.key ){
2591 **           RETURN_ROW
2592 **           while( csrStart.key + regStart) < csrCurrent.key ){
2593 **             AGGINVERSE
2594 **           }
2595 **         }
2596 **       }
2597 **     }
2598 **     flush:
2599 **       AGGSTEP
2600 **       while( 1 ){
2601 **         RETURN ROW
2602 **         if( csrCurrent is EOF ) break;
2603 **           while( csrStart.key + regStart) < csrCurrent.key ){
2604 **             AGGINVERSE
2605 **           }
2606 **         }
2607 **       }
2608 **
2609 ** In the above notation, "csr.key" means the current value of the ORDER BY
2610 ** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
2611 ** or <expr PRECEDING) read from cursor csr.
2612 **
2613 **   RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2614 **
2615 **     ... loop started by sqlite3WhereBegin() ...
2616 **       if( new partition ){
2617 **         Gosub flush
2618 **       }
2619 **       Insert new row into eph table.
2620 **       if( first row of partition ){
2621 **         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2622 **         regEnd = <expr2>
2623 **         regStart = <expr1>
2624 **       }else{
2625 **         while( (csrEnd.key + regEnd) <= csrCurrent.key ){
2626 **           AGGSTEP
2627 **         }
2628 **         while( (csrStart.key + regStart) < csrCurrent.key ){
2629 **           AGGINVERSE
2630 **         }
2631 **         RETURN_ROW
2632 **       }
2633 **     }
2634 **     flush:
2635 **       while( (csrEnd.key + regEnd) <= csrCurrent.key ){
2636 **         AGGSTEP
2637 **       }
2638 **       while( (csrStart.key + regStart) < csrCurrent.key ){
2639 **         AGGINVERSE
2640 **       }
2641 **       RETURN_ROW
2642 **
2643 **   RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2644 **
2645 **     ... loop started by sqlite3WhereBegin() ...
2646 **       if( new partition ){
2647 **         Gosub flush
2648 **       }
2649 **       Insert new row into eph table.
2650 **       if( first row of partition ){
2651 **         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2652 **         regEnd = <expr2>
2653 **         regStart = <expr1>
2654 **       }else{
2655 **         AGGSTEP
2656 **         while( (csrCurrent.key + regEnd) < csrEnd.key ){
2657 **           while( (csrCurrent.key + regStart) > csrStart.key ){
2658 **             AGGINVERSE
2659 **           }
2660 **           RETURN_ROW
2661 **         }
2662 **       }
2663 **     }
2664 **     flush:
2665 **       AGGSTEP
2666 **       while( 1 ){
2667 **         while( (csrCurrent.key + regStart) > csrStart.key ){
2668 **           AGGINVERSE
2669 **           if( eof ) break "while( 1 )" loop.
2670 **         }
2671 **         RETURN_ROW
2672 **       }
2673 **       while( !eof csrCurrent ){
2674 **         RETURN_ROW
2675 **       }
2676 **
2677 ** The text above leaves out many details. Refer to the code and comments
2678 ** below for a more complete picture.
2679 */
2680 void sqlite3WindowCodeStep(
2681   Parse *pParse,                  /* Parse context */
2682   Select *p,                      /* Rewritten SELECT statement */
2683   WhereInfo *pWInfo,              /* Context returned by sqlite3WhereBegin() */
2684   int regGosub,                   /* Register for OP_Gosub */
2685   int addrGosub                   /* OP_Gosub here to return each row */
2686 ){
2687   Window *pMWin = p->pWin;
2688   ExprList *pOrderBy = pMWin->pOrderBy;
2689   Vdbe *v = sqlite3GetVdbe(pParse);
2690   int csrWrite;                   /* Cursor used to write to eph. table */
2691   int csrInput = p->pSrc->a[0].iCursor;     /* Cursor of sub-select */
2692   int nInput = p->pSrc->a[0].pTab->nCol;    /* Number of cols returned by sub */
2693   int iInput;                               /* To iterate through sub cols */
2694   int addrNe;                     /* Address of OP_Ne */
2695   int addrGosubFlush = 0;         /* Address of OP_Gosub to flush: */
2696   int addrInteger = 0;            /* Address of OP_Integer */
2697   int addrEmpty;                  /* Address of OP_Rewind in flush: */
2698   int regNew;                     /* Array of registers holding new input row */
2699   int regRecord;                  /* regNew array in record form */
2700   int regRowid;                   /* Rowid for regRecord in eph table */
2701   int regNewPeer = 0;             /* Peer values for new row (part of regNew) */
2702   int regPeer = 0;                /* Peer values for current row */
2703   int regFlushPart = 0;           /* Register for "Gosub flush_partition" */
2704   WindowCodeArg s;                /* Context object for sub-routines */
2705   int lblWhereEnd;                /* Label just before sqlite3WhereEnd() code */
2706   int regStart = 0;               /* Value of <expr> PRECEDING */
2707   int regEnd = 0;                 /* Value of <expr> FOLLOWING */
2708 
2709   assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
2710        || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
2711   );
2712   assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
2713        || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
2714   );
2715   assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
2716        || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
2717        || pMWin->eExclude==TK_NO
2718   );
2719 
2720   lblWhereEnd = sqlite3VdbeMakeLabel(pParse);
2721 
2722   /* Fill in the context object */
2723   memset(&s, 0, sizeof(WindowCodeArg));
2724   s.pParse = pParse;
2725   s.pMWin = pMWin;
2726   s.pVdbe = v;
2727   s.regGosub = regGosub;
2728   s.addrGosub = addrGosub;
2729   s.current.csr = pMWin->iEphCsr;
2730   csrWrite = s.current.csr+1;
2731   s.start.csr = s.current.csr+2;
2732   s.end.csr = s.current.csr+3;
2733 
2734   /* Figure out when rows may be deleted from the ephemeral table. There
2735   ** are four options - they may never be deleted (eDelete==0), they may
2736   ** be deleted as soon as they are no longer part of the window frame
2737   ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
2738   ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
2739   ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
2740   switch( pMWin->eStart ){
2741     case TK_FOLLOWING:
2742       if( pMWin->eFrmType!=TK_RANGE
2743        && windowExprGtZero(pParse, pMWin->pStart)
2744       ){
2745         s.eDelete = WINDOW_RETURN_ROW;
2746       }
2747       break;
2748     case TK_UNBOUNDED:
2749       if( windowCacheFrame(pMWin)==0 ){
2750         if( pMWin->eEnd==TK_PRECEDING ){
2751           if( pMWin->eFrmType!=TK_RANGE
2752            && windowExprGtZero(pParse, pMWin->pEnd)
2753           ){
2754             s.eDelete = WINDOW_AGGSTEP;
2755           }
2756         }else{
2757           s.eDelete = WINDOW_RETURN_ROW;
2758         }
2759       }
2760       break;
2761     default:
2762       s.eDelete = WINDOW_AGGINVERSE;
2763       break;
2764   }
2765 
2766   /* Allocate registers for the array of values from the sub-query, the
2767   ** samve values in record form, and the rowid used to insert said record
2768   ** into the ephemeral table.  */
2769   regNew = pParse->nMem+1;
2770   pParse->nMem += nInput;
2771   regRecord = ++pParse->nMem;
2772   regRowid = ++pParse->nMem;
2773 
2774   /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
2775   ** clause, allocate registers to store the results of evaluating each
2776   ** <expr>.  */
2777   if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
2778     regStart = ++pParse->nMem;
2779   }
2780   if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
2781     regEnd = ++pParse->nMem;
2782   }
2783 
2784   /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
2785   ** registers to store copies of the ORDER BY expressions (peer values)
2786   ** for the main loop, and for each cursor (start, current and end). */
2787   if( pMWin->eFrmType!=TK_ROWS ){
2788     int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
2789     regNewPeer = regNew + pMWin->nBufferCol;
2790     if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
2791     regPeer = pParse->nMem+1;       pParse->nMem += nPeer;
2792     s.start.reg = pParse->nMem+1;   pParse->nMem += nPeer;
2793     s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
2794     s.end.reg = pParse->nMem+1;     pParse->nMem += nPeer;
2795   }
2796 
2797   /* Load the column values for the row returned by the sub-select
2798   ** into an array of registers starting at regNew. Assemble them into
2799   ** a record in register regRecord. */
2800   for(iInput=0; iInput<nInput; iInput++){
2801     sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
2802   }
2803   sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
2804 
2805   /* An input row has just been read into an array of registers starting
2806   ** at regNew. If the window has a PARTITION clause, this block generates
2807   ** VM code to check if the input row is the start of a new partition.
2808   ** If so, it does an OP_Gosub to an address to be filled in later. The
2809   ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
2810   if( pMWin->pPartition ){
2811     int addr;
2812     ExprList *pPart = pMWin->pPartition;
2813     int nPart = pPart->nExpr;
2814     int regNewPart = regNew + pMWin->nBufferCol;
2815     KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
2816 
2817     regFlushPart = ++pParse->nMem;
2818     addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
2819     sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
2820     sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
2821     VdbeCoverageEqNe(v);
2822     addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
2823     VdbeComment((v, "call flush_partition"));
2824     sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
2825   }
2826 
2827   /* Insert the new row into the ephemeral table */
2828   sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid);
2829   sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid);
2830   addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid);
2831   VdbeCoverageNeverNull(v);
2832 
2833   /* This block is run for the first row of each partition */
2834   s.regArg = windowInitAccum(pParse, pMWin);
2835 
2836   if( regStart ){
2837     sqlite3ExprCode(pParse, pMWin->pStart, regStart);
2838     windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE?3:0));
2839   }
2840   if( regEnd ){
2841     sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
2842     windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE?3:0));
2843   }
2844 
2845   if( pMWin->eFrmType!=TK_RANGE && pMWin->eStart==pMWin->eEnd && regStart ){
2846     int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
2847     int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
2848     VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */
2849     VdbeCoverageNeverNullIf(v, op==OP_Le); /*   values previously checked */
2850     windowAggFinal(&s, 0);
2851     sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
2852     VdbeCoverageNeverTaken(v);
2853     windowReturnOneRow(&s);
2854     sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
2855     sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
2856     sqlite3VdbeJumpHere(v, addrGe);
2857   }
2858   if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){
2859     assert( pMWin->eEnd==TK_FOLLOWING );
2860     sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
2861   }
2862 
2863   if( pMWin->eStart!=TK_UNBOUNDED ){
2864     sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1);
2865     VdbeCoverageNeverTaken(v);
2866   }
2867   sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
2868   VdbeCoverageNeverTaken(v);
2869   sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1);
2870   VdbeCoverageNeverTaken(v);
2871   if( regPeer && pOrderBy ){
2872     sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
2873     sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
2874     sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
2875     sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
2876   }
2877 
2878   sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
2879 
2880   sqlite3VdbeJumpHere(v, addrNe);
2881 
2882   /* Beginning of the block executed for the second and subsequent rows. */
2883   if( regPeer ){
2884     windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);
2885   }
2886   if( pMWin->eStart==TK_FOLLOWING ){
2887     windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
2888     if( pMWin->eEnd!=TK_UNBOUNDED ){
2889       if( pMWin->eFrmType==TK_RANGE ){
2890         int lbl = sqlite3VdbeMakeLabel(pParse);
2891         int addrNext = sqlite3VdbeCurrentAddr(v);
2892         windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2893         windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2894         windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2895         sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
2896         sqlite3VdbeResolveLabel(v, lbl);
2897       }else{
2898         windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
2899         windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2900       }
2901     }
2902   }else
2903   if( pMWin->eEnd==TK_PRECEDING ){
2904     int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
2905     windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
2906     if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2907     windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2908     if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2909   }else{
2910     int addr = 0;
2911     windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
2912     if( pMWin->eEnd!=TK_UNBOUNDED ){
2913       if( pMWin->eFrmType==TK_RANGE ){
2914         int lbl = 0;
2915         addr = sqlite3VdbeCurrentAddr(v);
2916         if( regEnd ){
2917           lbl = sqlite3VdbeMakeLabel(pParse);
2918           windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2919         }
2920         windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2921         windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2922         if( regEnd ){
2923           sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
2924           sqlite3VdbeResolveLabel(v, lbl);
2925         }
2926       }else{
2927         if( regEnd ){
2928           addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
2929           VdbeCoverage(v);
2930         }
2931         windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2932         windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2933         if( regEnd ) sqlite3VdbeJumpHere(v, addr);
2934       }
2935     }
2936   }
2937 
2938   /* End of the main input loop */
2939   sqlite3VdbeResolveLabel(v, lblWhereEnd);
2940   sqlite3WhereEnd(pWInfo);
2941 
2942   /* Fall through */
2943   if( pMWin->pPartition ){
2944     addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
2945     sqlite3VdbeJumpHere(v, addrGosubFlush);
2946   }
2947 
2948   addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
2949   VdbeCoverage(v);
2950   if( pMWin->eEnd==TK_PRECEDING ){
2951     int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
2952     windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
2953     if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2954     windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2955   }else if( pMWin->eStart==TK_FOLLOWING ){
2956     int addrStart;
2957     int addrBreak1;
2958     int addrBreak2;
2959     int addrBreak3;
2960     windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
2961     if( pMWin->eFrmType==TK_RANGE ){
2962       addrStart = sqlite3VdbeCurrentAddr(v);
2963       addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
2964       addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
2965     }else
2966     if( pMWin->eEnd==TK_UNBOUNDED ){
2967       addrStart = sqlite3VdbeCurrentAddr(v);
2968       addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
2969       addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
2970     }else{
2971       assert( pMWin->eEnd==TK_FOLLOWING );
2972       addrStart = sqlite3VdbeCurrentAddr(v);
2973       addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
2974       addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
2975     }
2976     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2977     sqlite3VdbeJumpHere(v, addrBreak2);
2978     addrStart = sqlite3VdbeCurrentAddr(v);
2979     addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
2980     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2981     sqlite3VdbeJumpHere(v, addrBreak1);
2982     sqlite3VdbeJumpHere(v, addrBreak3);
2983   }else{
2984     int addrBreak;
2985     int addrStart;
2986     windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
2987     addrStart = sqlite3VdbeCurrentAddr(v);
2988     addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
2989     windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2990     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2991     sqlite3VdbeJumpHere(v, addrBreak);
2992   }
2993   sqlite3VdbeJumpHere(v, addrEmpty);
2994 
2995   sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
2996   if( pMWin->pPartition ){
2997     if( pMWin->regStartRowid ){
2998       sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
2999       sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
3000     }
3001     sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
3002     sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
3003   }
3004 }
3005 
3006 #endif /* SQLITE_OMIT_WINDOWFUNC */
3007