xref: /sqlite-3.40.0/src/window.c (revision 6b6ec407)
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       /* no break */ deliberate_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         int f = pExpr->flags & EP_Collate;
807         assert( ExprHasProperty(pExpr, EP_Static)==0 );
808         ExprSetProperty(pExpr, EP_Static);
809         sqlite3ExprDelete(pParse->db, pExpr);
810         ExprClearProperty(pExpr, EP_Static);
811         memset(pExpr, 0, sizeof(Expr));
812 
813         pExpr->op = TK_COLUMN;
814         pExpr->iColumn = (iCol<0 ? p->pSub->nExpr-1: iCol);
815         pExpr->iTable = p->pWin->iEphCsr;
816         pExpr->y.pTab = p->pTab;
817         pExpr->flags = f;
818       }
819       if( pParse->db->mallocFailed ) return WRC_Abort;
820       break;
821     }
822 
823     default: /* no-op */
824       break;
825   }
826 
827   return WRC_Continue;
828 }
829 static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
830   struct WindowRewrite *p = pWalker->u.pRewrite;
831   Select *pSave = p->pSubSelect;
832   if( pSave==pSelect ){
833     return WRC_Continue;
834   }else{
835     p->pSubSelect = pSelect;
836     sqlite3WalkSelect(pWalker, pSelect);
837     p->pSubSelect = pSave;
838   }
839   return WRC_Prune;
840 }
841 
842 
843 /*
844 ** Iterate through each expression in expression-list pEList. For each:
845 **
846 **   * TK_COLUMN,
847 **   * aggregate function, or
848 **   * window function with a Window object that is not a member of the
849 **     Window list passed as the second argument (pWin).
850 **
851 ** Append the node to output expression-list (*ppSub). And replace it
852 ** with a TK_COLUMN that reads the (N-1)th element of table
853 ** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
854 ** appending the new one.
855 */
856 static void selectWindowRewriteEList(
857   Parse *pParse,
858   Window *pWin,
859   SrcList *pSrc,
860   ExprList *pEList,               /* Rewrite expressions in this list */
861   Table *pTab,
862   ExprList **ppSub                /* IN/OUT: Sub-select expression-list */
863 ){
864   Walker sWalker;
865   WindowRewrite sRewrite;
866 
867   assert( pWin!=0 );
868   memset(&sWalker, 0, sizeof(Walker));
869   memset(&sRewrite, 0, sizeof(WindowRewrite));
870 
871   sRewrite.pSub = *ppSub;
872   sRewrite.pWin = pWin;
873   sRewrite.pSrc = pSrc;
874   sRewrite.pTab = pTab;
875 
876   sWalker.pParse = pParse;
877   sWalker.xExprCallback = selectWindowRewriteExprCb;
878   sWalker.xSelectCallback = selectWindowRewriteSelectCb;
879   sWalker.u.pRewrite = &sRewrite;
880 
881   (void)sqlite3WalkExprList(&sWalker, pEList);
882 
883   *ppSub = sRewrite.pSub;
884 }
885 
886 /*
887 ** Append a copy of each expression in expression-list pAppend to
888 ** expression list pList. Return a pointer to the result list.
889 */
890 static ExprList *exprListAppendList(
891   Parse *pParse,          /* Parsing context */
892   ExprList *pList,        /* List to which to append. Might be NULL */
893   ExprList *pAppend,      /* List of values to append. Might be NULL */
894   int bIntToNull
895 ){
896   if( pAppend ){
897     int i;
898     int nInit = pList ? pList->nExpr : 0;
899     for(i=0; i<pAppend->nExpr; i++){
900       sqlite3 *db = pParse->db;
901       Expr *pDup = sqlite3ExprDup(db, pAppend->a[i].pExpr, 0);
902       assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );
903       if( bIntToNull && db->mallocFailed==0 ){
904         int iDummy;
905         Expr *pSub;
906         for(pSub=pDup; ExprHasProperty(pSub, EP_Skip); pSub=pSub->pLeft){
907           assert( pSub );
908         }
909         if( sqlite3ExprIsInteger(pSub, &iDummy) ){
910           pSub->op = TK_NULL;
911           pSub->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
912           pSub->u.zToken = 0;
913         }
914       }
915       pList = sqlite3ExprListAppend(pParse, pList, pDup);
916       if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;
917     }
918   }
919   return pList;
920 }
921 
922 /*
923 ** When rewriting a query, if the new subquery in the FROM clause
924 ** contains TK_AGG_FUNCTION nodes that refer to an outer query,
925 ** then we have to increase the Expr->op2 values of those nodes
926 ** due to the extra subquery layer that was added.
927 **
928 ** See also the incrAggDepth() routine in resolve.c
929 */
930 static int sqlite3WindowExtraAggFuncDepth(Walker *pWalker, Expr *pExpr){
931   if( pExpr->op==TK_AGG_FUNCTION
932    && pExpr->op2>=pWalker->walkerDepth
933   ){
934     pExpr->op2++;
935   }
936   return WRC_Continue;
937 }
938 
939 /*
940 ** If the SELECT statement passed as the second argument does not invoke
941 ** any SQL window functions, this function is a no-op. Otherwise, it
942 ** rewrites the SELECT statement so that window function xStep functions
943 ** are invoked in the correct order as described under "SELECT REWRITING"
944 ** at the top of this file.
945 */
946 int sqlite3WindowRewrite(Parse *pParse, Select *p){
947   int rc = SQLITE_OK;
948   if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){
949     Vdbe *v = sqlite3GetVdbe(pParse);
950     sqlite3 *db = pParse->db;
951     Select *pSub = 0;             /* The subquery */
952     SrcList *pSrc = p->pSrc;
953     Expr *pWhere = p->pWhere;
954     ExprList *pGroupBy = p->pGroupBy;
955     Expr *pHaving = p->pHaving;
956     ExprList *pSort = 0;
957 
958     ExprList *pSublist = 0;       /* Expression list for sub-query */
959     Window *pMWin = p->pWin;      /* Main window object */
960     Window *pWin;                 /* Window object iterator */
961     Table *pTab;
962     Walker w;
963 
964     u32 selFlags = p->selFlags;
965 
966     pTab = sqlite3DbMallocZero(db, sizeof(Table));
967     if( pTab==0 ){
968       return sqlite3ErrorToParser(db, SQLITE_NOMEM);
969     }
970     sqlite3AggInfoPersistWalkerInit(&w, pParse);
971     sqlite3WalkSelect(&w, p);
972 
973     p->pSrc = 0;
974     p->pWhere = 0;
975     p->pGroupBy = 0;
976     p->pHaving = 0;
977     p->selFlags &= ~SF_Aggregate;
978     p->selFlags |= SF_WinRewrite;
979 
980     /* Create the ORDER BY clause for the sub-select. This is the concatenation
981     ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
982     ** redundant, remove the ORDER BY from the parent SELECT.  */
983     pSort = exprListAppendList(pParse, 0, pMWin->pPartition, 1);
984     pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);
985     if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){
986       int nSave = pSort->nExpr;
987       pSort->nExpr = p->pOrderBy->nExpr;
988       if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
989         sqlite3ExprListDelete(db, p->pOrderBy);
990         p->pOrderBy = 0;
991       }
992       pSort->nExpr = nSave;
993     }
994 
995     /* Assign a cursor number for the ephemeral table used to buffer rows.
996     ** The OpenEphemeral instruction is coded later, after it is known how
997     ** many columns the table will have.  */
998     pMWin->iEphCsr = pParse->nTab++;
999     pParse->nTab += 3;
1000 
1001     selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);
1002     selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);
1003     pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
1004 
1005     /* Append the PARTITION BY and ORDER BY expressions to the to the
1006     ** sub-select expression list. They are required to figure out where
1007     ** boundaries for partitions and sets of peer rows lie.  */
1008     pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);
1009     pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);
1010 
1011     /* Append the arguments passed to each window function to the
1012     ** sub-select expression list. Also allocate two registers for each
1013     ** window function - one for the accumulator, another for interim
1014     ** results.  */
1015     for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1016       ExprList *pArgs = pWin->pOwner->x.pList;
1017       if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){
1018         selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);
1019         pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
1020         pWin->bExprArgs = 1;
1021       }else{
1022         pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
1023         pSublist = exprListAppendList(pParse, pSublist, pArgs, 0);
1024       }
1025       if( pWin->pFilter ){
1026         Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
1027         pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
1028       }
1029       pWin->regAccum = ++pParse->nMem;
1030       pWin->regResult = ++pParse->nMem;
1031       sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1032     }
1033 
1034     /* If there is no ORDER BY or PARTITION BY clause, and the window
1035     ** function accepts zero arguments, and there are no other columns
1036     ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
1037     ** that pSublist is still NULL here. Add a constant expression here to
1038     ** keep everything legal in this case.
1039     */
1040     if( pSublist==0 ){
1041       pSublist = sqlite3ExprListAppend(pParse, 0,
1042         sqlite3Expr(db, TK_INTEGER, "0")
1043       );
1044     }
1045 
1046     pSub = sqlite3SelectNew(
1047         pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
1048     );
1049     SELECTTRACE(1,pParse,pSub,
1050        ("New window-function subquery in FROM clause of (%u/%p)\n",
1051        p->selId, p));
1052     p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
1053     if( p->pSrc ){
1054       Table *pTab2;
1055       p->pSrc->a[0].pSelect = pSub;
1056       sqlite3SrcListAssignCursors(pParse, p->pSrc);
1057       pSub->selFlags |= SF_Expanded;
1058       pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);
1059       pSub->selFlags |= (selFlags & SF_Aggregate);
1060       if( pTab2==0 ){
1061         /* Might actually be some other kind of error, but in that case
1062         ** pParse->nErr will be set, so if SQLITE_NOMEM is set, we will get
1063         ** the correct error message regardless. */
1064         rc = SQLITE_NOMEM;
1065       }else{
1066         memcpy(pTab, pTab2, sizeof(Table));
1067         pTab->tabFlags |= TF_Ephemeral;
1068         p->pSrc->a[0].pTab = pTab;
1069         pTab = pTab2;
1070         memset(&w, 0, sizeof(w));
1071         w.xExprCallback = sqlite3WindowExtraAggFuncDepth;
1072         w.xSelectCallback = sqlite3WalkerDepthIncrease;
1073         w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
1074         sqlite3WalkSelect(&w, pSub);
1075       }
1076     }else{
1077       sqlite3SelectDelete(db, pSub);
1078     }
1079     if( db->mallocFailed ) rc = SQLITE_NOMEM;
1080     sqlite3DbFree(db, pTab);
1081   }
1082 
1083   if( rc ){
1084     if( pParse->nErr==0 ){
1085       assert( pParse->db->mallocFailed );
1086       sqlite3ErrorToParser(pParse->db, SQLITE_NOMEM);
1087     }
1088   }
1089   return rc;
1090 }
1091 
1092 /*
1093 ** Unlink the Window object from the Select to which it is attached,
1094 ** if it is attached.
1095 */
1096 void sqlite3WindowUnlinkFromSelect(Window *p){
1097   if( p->ppThis ){
1098     *p->ppThis = p->pNextWin;
1099     if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis;
1100     p->ppThis = 0;
1101   }
1102 }
1103 
1104 /*
1105 ** Free the Window object passed as the second argument.
1106 */
1107 void sqlite3WindowDelete(sqlite3 *db, Window *p){
1108   if( p ){
1109     sqlite3WindowUnlinkFromSelect(p);
1110     sqlite3ExprDelete(db, p->pFilter);
1111     sqlite3ExprListDelete(db, p->pPartition);
1112     sqlite3ExprListDelete(db, p->pOrderBy);
1113     sqlite3ExprDelete(db, p->pEnd);
1114     sqlite3ExprDelete(db, p->pStart);
1115     sqlite3DbFree(db, p->zName);
1116     sqlite3DbFree(db, p->zBase);
1117     sqlite3DbFree(db, p);
1118   }
1119 }
1120 
1121 /*
1122 ** Free the linked list of Window objects starting at the second argument.
1123 */
1124 void sqlite3WindowListDelete(sqlite3 *db, Window *p){
1125   while( p ){
1126     Window *pNext = p->pNextWin;
1127     sqlite3WindowDelete(db, p);
1128     p = pNext;
1129   }
1130 }
1131 
1132 /*
1133 ** The argument expression is an PRECEDING or FOLLOWING offset.  The
1134 ** value should be a non-negative integer.  If the value is not a
1135 ** constant, change it to NULL.  The fact that it is then a non-negative
1136 ** integer will be caught later.  But it is important not to leave
1137 ** variable values in the expression tree.
1138 */
1139 static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
1140   if( 0==sqlite3ExprIsConstant(pExpr) ){
1141     if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
1142     sqlite3ExprDelete(pParse->db, pExpr);
1143     pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
1144   }
1145   return pExpr;
1146 }
1147 
1148 /*
1149 ** Allocate and return a new Window object describing a Window Definition.
1150 */
1151 Window *sqlite3WindowAlloc(
1152   Parse *pParse,    /* Parsing context */
1153   int eType,        /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */
1154   int eStart,       /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
1155   Expr *pStart,     /* Start window size if TK_PRECEDING or FOLLOWING */
1156   int eEnd,         /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
1157   Expr *pEnd,       /* End window size if TK_FOLLOWING or PRECEDING */
1158   u8 eExclude       /* EXCLUDE clause */
1159 ){
1160   Window *pWin = 0;
1161   int bImplicitFrame = 0;
1162 
1163   /* Parser assures the following: */
1164   assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
1165   assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
1166            || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
1167   assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
1168            || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
1169   assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
1170   assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
1171 
1172   if( eType==0 ){
1173     bImplicitFrame = 1;
1174     eType = TK_RANGE;
1175   }
1176 
1177   /* Additionally, the
1178   ** starting boundary type may not occur earlier in the following list than
1179   ** the ending boundary type:
1180   **
1181   **   UNBOUNDED PRECEDING
1182   **   <expr> PRECEDING
1183   **   CURRENT ROW
1184   **   <expr> FOLLOWING
1185   **   UNBOUNDED FOLLOWING
1186   **
1187   ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
1188   ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
1189   ** frame boundary.
1190   */
1191   if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
1192    || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
1193   ){
1194     sqlite3ErrorMsg(pParse, "unsupported frame specification");
1195     goto windowAllocErr;
1196   }
1197 
1198   pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
1199   if( pWin==0 ) goto windowAllocErr;
1200   pWin->eFrmType = eType;
1201   pWin->eStart = eStart;
1202   pWin->eEnd = eEnd;
1203   if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){
1204     eExclude = TK_NO;
1205   }
1206   pWin->eExclude = eExclude;
1207   pWin->bImplicitFrame = bImplicitFrame;
1208   pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
1209   pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
1210   return pWin;
1211 
1212 windowAllocErr:
1213   sqlite3ExprDelete(pParse->db, pEnd);
1214   sqlite3ExprDelete(pParse->db, pStart);
1215   return 0;
1216 }
1217 
1218 /*
1219 ** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
1220 ** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
1221 ** equivalent nul-terminated string.
1222 */
1223 Window *sqlite3WindowAssemble(
1224   Parse *pParse,
1225   Window *pWin,
1226   ExprList *pPartition,
1227   ExprList *pOrderBy,
1228   Token *pBase
1229 ){
1230   if( pWin ){
1231     pWin->pPartition = pPartition;
1232     pWin->pOrderBy = pOrderBy;
1233     if( pBase ){
1234       pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
1235     }
1236   }else{
1237     sqlite3ExprListDelete(pParse->db, pPartition);
1238     sqlite3ExprListDelete(pParse->db, pOrderBy);
1239   }
1240   return pWin;
1241 }
1242 
1243 /*
1244 ** Window *pWin has just been created from a WINDOW clause. Tokne pBase
1245 ** is the base window. Earlier windows from the same WINDOW clause are
1246 ** stored in the linked list starting at pWin->pNextWin. This function
1247 ** either updates *pWin according to the base specification, or else
1248 ** leaves an error in pParse.
1249 */
1250 void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
1251   if( pWin->zBase ){
1252     sqlite3 *db = pParse->db;
1253     Window *pExist = windowFind(pParse, pList, pWin->zBase);
1254     if( pExist ){
1255       const char *zErr = 0;
1256       /* Check for errors */
1257       if( pWin->pPartition ){
1258         zErr = "PARTITION clause";
1259       }else if( pExist->pOrderBy && pWin->pOrderBy ){
1260         zErr = "ORDER BY clause";
1261       }else if( pExist->bImplicitFrame==0 ){
1262         zErr = "frame specification";
1263       }
1264       if( zErr ){
1265         sqlite3ErrorMsg(pParse,
1266             "cannot override %s of window: %s", zErr, pWin->zBase
1267         );
1268       }else{
1269         pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
1270         if( pExist->pOrderBy ){
1271           assert( pWin->pOrderBy==0 );
1272           pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
1273         }
1274         sqlite3DbFree(db, pWin->zBase);
1275         pWin->zBase = 0;
1276       }
1277     }
1278   }
1279 }
1280 
1281 /*
1282 ** Attach window object pWin to expression p.
1283 */
1284 void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
1285   if( p ){
1286     assert( p->op==TK_FUNCTION );
1287     assert( pWin );
1288     p->y.pWin = pWin;
1289     ExprSetProperty(p, EP_WinFunc);
1290     pWin->pOwner = p;
1291     if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){
1292       sqlite3ErrorMsg(pParse,
1293           "DISTINCT is not supported for window functions"
1294       );
1295     }
1296   }else{
1297     sqlite3WindowDelete(pParse->db, pWin);
1298   }
1299 }
1300 
1301 /*
1302 ** Possibly link window pWin into the list at pSel->pWin (window functions
1303 ** to be processed as part of SELECT statement pSel). The window is linked
1304 ** in if either (a) there are no other windows already linked to this
1305 ** SELECT, or (b) the windows already linked use a compatible window frame.
1306 */
1307 void sqlite3WindowLink(Select *pSel, Window *pWin){
1308   if( pSel ){
1309     if( 0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0) ){
1310       pWin->pNextWin = pSel->pWin;
1311       if( pSel->pWin ){
1312         pSel->pWin->ppThis = &pWin->pNextWin;
1313       }
1314       pSel->pWin = pWin;
1315       pWin->ppThis = &pSel->pWin;
1316     }else{
1317       if( sqlite3ExprListCompare(pWin->pPartition, pSel->pWin->pPartition,-1) ){
1318         pSel->selFlags |= SF_MultiPart;
1319       }
1320     }
1321   }
1322 }
1323 
1324 /*
1325 ** Return 0 if the two window objects are identical, 1 if they are
1326 ** different, or 2 if it cannot be determined if the objects are identical
1327 ** or not. Identical window objects can be processed in a single scan.
1328 */
1329 int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2, int bFilter){
1330   int res;
1331   if( NEVER(p1==0) || NEVER(p2==0) ) return 1;
1332   if( p1->eFrmType!=p2->eFrmType ) return 1;
1333   if( p1->eStart!=p2->eStart ) return 1;
1334   if( p1->eEnd!=p2->eEnd ) return 1;
1335   if( p1->eExclude!=p2->eExclude ) return 1;
1336   if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
1337   if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
1338   if( (res = sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1)) ){
1339     return res;
1340   }
1341   if( (res = sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1)) ){
1342     return res;
1343   }
1344   if( bFilter ){
1345     if( (res = sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1)) ){
1346       return res;
1347     }
1348   }
1349   return 0;
1350 }
1351 
1352 
1353 /*
1354 ** This is called by code in select.c before it calls sqlite3WhereBegin()
1355 ** to begin iterating through the sub-query results. It is used to allocate
1356 ** and initialize registers and cursors used by sqlite3WindowCodeStep().
1357 */
1358 void sqlite3WindowCodeInit(Parse *pParse, Select *pSelect){
1359   int nEphExpr = pSelect->pSrc->a[0].pSelect->pEList->nExpr;
1360   Window *pMWin = pSelect->pWin;
1361   Window *pWin;
1362   Vdbe *v = sqlite3GetVdbe(pParse);
1363 
1364   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr);
1365   sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
1366   sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
1367   sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
1368 
1369   /* Allocate registers to use for PARTITION BY values, if any. Initialize
1370   ** said registers to NULL.  */
1371   if( pMWin->pPartition ){
1372     int nExpr = pMWin->pPartition->nExpr;
1373     pMWin->regPart = pParse->nMem+1;
1374     pParse->nMem += nExpr;
1375     sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
1376   }
1377 
1378   pMWin->regOne = ++pParse->nMem;
1379   sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
1380 
1381   if( pMWin->eExclude ){
1382     pMWin->regStartRowid = ++pParse->nMem;
1383     pMWin->regEndRowid = ++pParse->nMem;
1384     pMWin->csrApp = pParse->nTab++;
1385     sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
1386     sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
1387     sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
1388     return;
1389   }
1390 
1391   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1392     FuncDef *p = pWin->pFunc;
1393     if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
1394       /* The inline versions of min() and max() require a single ephemeral
1395       ** table and 3 registers. The registers are used as follows:
1396       **
1397       **   regApp+0: slot to copy min()/max() argument to for MakeRecord
1398       **   regApp+1: integer value used to ensure keys are unique
1399       **   regApp+2: output of MakeRecord
1400       */
1401       ExprList *pList = pWin->pOwner->x.pList;
1402       KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
1403       pWin->csrApp = pParse->nTab++;
1404       pWin->regApp = pParse->nMem+1;
1405       pParse->nMem += 3;
1406       if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
1407         assert( pKeyInfo->aSortFlags[0]==0 );
1408         pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC;
1409       }
1410       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
1411       sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
1412       sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1413     }
1414     else if( p->zName==nth_valueName || p->zName==first_valueName ){
1415       /* Allocate two registers at pWin->regApp. These will be used to
1416       ** store the start and end index of the current frame.  */
1417       pWin->regApp = pParse->nMem+1;
1418       pWin->csrApp = pParse->nTab++;
1419       pParse->nMem += 2;
1420       sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1421     }
1422     else if( p->zName==leadName || p->zName==lagName ){
1423       pWin->csrApp = pParse->nTab++;
1424       sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1425     }
1426   }
1427 }
1428 
1429 #define WINDOW_STARTING_INT  0
1430 #define WINDOW_ENDING_INT    1
1431 #define WINDOW_NTH_VALUE_INT 2
1432 #define WINDOW_STARTING_NUM  3
1433 #define WINDOW_ENDING_NUM    4
1434 
1435 /*
1436 ** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
1437 ** value of the second argument to nth_value() (eCond==2) has just been
1438 ** evaluated and the result left in register reg. This function generates VM
1439 ** code to check that the value is a non-negative integer and throws an
1440 ** exception if it is not.
1441 */
1442 static void windowCheckValue(Parse *pParse, int reg, int eCond){
1443   static const char *azErr[] = {
1444     "frame starting offset must be a non-negative integer",
1445     "frame ending offset must be a non-negative integer",
1446     "second argument to nth_value must be a positive integer",
1447     "frame starting offset must be a non-negative number",
1448     "frame ending offset must be a non-negative number",
1449   };
1450   static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };
1451   Vdbe *v = sqlite3GetVdbe(pParse);
1452   int regZero = sqlite3GetTempReg(pParse);
1453   assert( eCond>=0 && eCond<ArraySize(azErr) );
1454   sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
1455   if( eCond>=WINDOW_STARTING_NUM ){
1456     int regString = sqlite3GetTempReg(pParse);
1457     sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
1458     sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);
1459     sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL);
1460     VdbeCoverage(v);
1461     assert( eCond==3 || eCond==4 );
1462     VdbeCoverageIf(v, eCond==3);
1463     VdbeCoverageIf(v, eCond==4);
1464   }else{
1465     sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
1466     VdbeCoverage(v);
1467     assert( eCond==0 || eCond==1 || eCond==2 );
1468     VdbeCoverageIf(v, eCond==0);
1469     VdbeCoverageIf(v, eCond==1);
1470     VdbeCoverageIf(v, eCond==2);
1471   }
1472   sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
1473   sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC);
1474   VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */
1475   VdbeCoverageNeverNullIf(v, eCond==1); /*   the OP_MustBeInt */
1476   VdbeCoverageNeverNullIf(v, eCond==2);
1477   VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */
1478   VdbeCoverageNeverNullIf(v, eCond==4); /*   the OP_Ge */
1479   sqlite3MayAbort(pParse);
1480   sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
1481   sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
1482   sqlite3ReleaseTempReg(pParse, regZero);
1483 }
1484 
1485 /*
1486 ** Return the number of arguments passed to the window-function associated
1487 ** with the object passed as the only argument to this function.
1488 */
1489 static int windowArgCount(Window *pWin){
1490   ExprList *pList = pWin->pOwner->x.pList;
1491   return (pList ? pList->nExpr : 0);
1492 }
1493 
1494 typedef struct WindowCodeArg WindowCodeArg;
1495 typedef struct WindowCsrAndReg WindowCsrAndReg;
1496 
1497 /*
1498 ** See comments above struct WindowCodeArg.
1499 */
1500 struct WindowCsrAndReg {
1501   int csr;                        /* Cursor number */
1502   int reg;                        /* First in array of peer values */
1503 };
1504 
1505 /*
1506 ** A single instance of this structure is allocated on the stack by
1507 ** sqlite3WindowCodeStep() and a pointer to it passed to the various helper
1508 ** routines. This is to reduce the number of arguments required by each
1509 ** helper function.
1510 **
1511 ** regArg:
1512 **   Each window function requires an accumulator register (just as an
1513 **   ordinary aggregate function does). This variable is set to the first
1514 **   in an array of accumulator registers - one for each window function
1515 **   in the WindowCodeArg.pMWin list.
1516 **
1517 ** eDelete:
1518 **   The window functions implementation sometimes caches the input rows
1519 **   that it processes in a temporary table. If it is not zero, this
1520 **   variable indicates when rows may be removed from the temp table (in
1521 **   order to reduce memory requirements - it would always be safe just
1522 **   to leave them there). Possible values for eDelete are:
1523 **
1524 **      WINDOW_RETURN_ROW:
1525 **        An input row can be discarded after it is returned to the caller.
1526 **
1527 **      WINDOW_AGGINVERSE:
1528 **        An input row can be discarded after the window functions xInverse()
1529 **        callbacks have been invoked in it.
1530 **
1531 **      WINDOW_AGGSTEP:
1532 **        An input row can be discarded after the window functions xStep()
1533 **        callbacks have been invoked in it.
1534 **
1535 ** start,current,end
1536 **   Consider a window-frame similar to the following:
1537 **
1538 **     (ORDER BY a, b GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING)
1539 **
1540 **   The windows functions implmentation caches the input rows in a temp
1541 **   table, sorted by "a, b" (it actually populates the cache lazily, and
1542 **   aggressively removes rows once they are no longer required, but that's
1543 **   a mere detail). It keeps three cursors open on the temp table. One
1544 **   (current) that points to the next row to return to the query engine
1545 **   once its window function values have been calculated. Another (end)
1546 **   points to the next row to call the xStep() method of each window function
1547 **   on (so that it is 2 groups ahead of current). And a third (start) that
1548 **   points to the next row to call the xInverse() method of each window
1549 **   function on.
1550 **
1551 **   Each cursor (start, current and end) consists of a VDBE cursor
1552 **   (WindowCsrAndReg.csr) and an array of registers (starting at
1553 **   WindowCodeArg.reg) that always contains a copy of the peer values
1554 **   read from the corresponding cursor.
1555 **
1556 **   Depending on the window-frame in question, all three cursors may not
1557 **   be required. In this case both WindowCodeArg.csr and reg are set to
1558 **   0.
1559 */
1560 struct WindowCodeArg {
1561   Parse *pParse;             /* Parse context */
1562   Window *pMWin;             /* First in list of functions being processed */
1563   Vdbe *pVdbe;               /* VDBE object */
1564   int addrGosub;             /* OP_Gosub to this address to return one row */
1565   int regGosub;              /* Register used with OP_Gosub(addrGosub) */
1566   int regArg;                /* First in array of accumulator registers */
1567   int eDelete;               /* See above */
1568 
1569   WindowCsrAndReg start;
1570   WindowCsrAndReg current;
1571   WindowCsrAndReg end;
1572 };
1573 
1574 /*
1575 ** Generate VM code to read the window frames peer values from cursor csr into
1576 ** an array of registers starting at reg.
1577 */
1578 static void windowReadPeerValues(
1579   WindowCodeArg *p,
1580   int csr,
1581   int reg
1582 ){
1583   Window *pMWin = p->pMWin;
1584   ExprList *pOrderBy = pMWin->pOrderBy;
1585   if( pOrderBy ){
1586     Vdbe *v = sqlite3GetVdbe(p->pParse);
1587     ExprList *pPart = pMWin->pPartition;
1588     int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
1589     int i;
1590     for(i=0; i<pOrderBy->nExpr; i++){
1591       sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
1592     }
1593   }
1594 }
1595 
1596 /*
1597 ** Generate VM code to invoke either xStep() (if bInverse is 0) or
1598 ** xInverse (if bInverse is non-zero) for each window function in the
1599 ** linked list starting at pMWin. Or, for built-in window functions
1600 ** that do not use the standard function API, generate the required
1601 ** inline VM code.
1602 **
1603 ** If argument csr is greater than or equal to 0, then argument reg is
1604 ** the first register in an array of registers guaranteed to be large
1605 ** enough to hold the array of arguments for each function. In this case
1606 ** the arguments are extracted from the current row of csr into the
1607 ** array of registers before invoking OP_AggStep or OP_AggInverse
1608 **
1609 ** Or, if csr is less than zero, then the array of registers at reg is
1610 ** already populated with all columns from the current row of the sub-query.
1611 **
1612 ** If argument regPartSize is non-zero, then it is a register containing the
1613 ** number of rows in the current partition.
1614 */
1615 static void windowAggStep(
1616   WindowCodeArg *p,
1617   Window *pMWin,                  /* Linked list of window functions */
1618   int csr,                        /* Read arguments from this cursor */
1619   int bInverse,                   /* True to invoke xInverse instead of xStep */
1620   int reg                         /* Array of registers */
1621 ){
1622   Parse *pParse = p->pParse;
1623   Vdbe *v = sqlite3GetVdbe(pParse);
1624   Window *pWin;
1625   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1626     FuncDef *pFunc = pWin->pFunc;
1627     int regArg;
1628     int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin);
1629     int i;
1630 
1631     assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED );
1632 
1633     /* All OVER clauses in the same window function aggregate step must
1634     ** be the same. */
1635     assert( pWin==pMWin || sqlite3WindowCompare(pParse,pWin,pMWin,0)!=1 );
1636 
1637     for(i=0; i<nArg; i++){
1638       if( i!=1 || pFunc->zName!=nth_valueName ){
1639         sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
1640       }else{
1641         sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
1642       }
1643     }
1644     regArg = reg;
1645 
1646     if( pMWin->regStartRowid==0
1647      && (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1648      && (pWin->eStart!=TK_UNBOUNDED)
1649     ){
1650       int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
1651       VdbeCoverage(v);
1652       if( bInverse==0 ){
1653         sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
1654         sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
1655         sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
1656         sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
1657       }else{
1658         sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
1659         VdbeCoverageNeverTaken(v);
1660         sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
1661         sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1662       }
1663       sqlite3VdbeJumpHere(v, addrIsNull);
1664     }else if( pWin->regApp ){
1665       assert( pFunc->zName==nth_valueName
1666            || pFunc->zName==first_valueName
1667       );
1668       assert( bInverse==0 || bInverse==1 );
1669       sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
1670     }else if( pFunc->xSFunc!=noopStepFunc ){
1671       int addrIf = 0;
1672       if( pWin->pFilter ){
1673         int regTmp;
1674         assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr );
1675         assert( pWin->bExprArgs || nArg  ||pWin->pOwner->x.pList==0 );
1676         regTmp = sqlite3GetTempReg(pParse);
1677         sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
1678         addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
1679         VdbeCoverage(v);
1680         sqlite3ReleaseTempReg(pParse, regTmp);
1681       }
1682 
1683       if( pWin->bExprArgs ){
1684         int iStart = sqlite3VdbeCurrentAddr(v);
1685         VdbeOp *pOp, *pEnd;
1686 
1687         nArg = pWin->pOwner->x.pList->nExpr;
1688         regArg = sqlite3GetTempRange(pParse, nArg);
1689         sqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0);
1690 
1691         pEnd = sqlite3VdbeGetOp(v, -1);
1692         for(pOp=sqlite3VdbeGetOp(v, iStart); pOp<=pEnd; pOp++){
1693           if( pOp->opcode==OP_Column && pOp->p1==pWin->iEphCsr ){
1694             pOp->p1 = csr;
1695           }
1696         }
1697       }
1698       if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
1699         CollSeq *pColl;
1700         assert( nArg>0 );
1701         pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
1702         sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
1703       }
1704       sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
1705                         bInverse, regArg, pWin->regAccum);
1706       sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
1707       sqlite3VdbeChangeP5(v, (u8)nArg);
1708       if( pWin->bExprArgs ){
1709         sqlite3ReleaseTempRange(pParse, regArg, nArg);
1710       }
1711       if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
1712     }
1713   }
1714 }
1715 
1716 /*
1717 ** Values that may be passed as the second argument to windowCodeOp().
1718 */
1719 #define WINDOW_RETURN_ROW 1
1720 #define WINDOW_AGGINVERSE 2
1721 #define WINDOW_AGGSTEP    3
1722 
1723 /*
1724 ** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
1725 ** (bFin==1) for each window function in the linked list starting at
1726 ** pMWin. Or, for built-in window-functions that do not use the standard
1727 ** API, generate the equivalent VM code.
1728 */
1729 static void windowAggFinal(WindowCodeArg *p, int bFin){
1730   Parse *pParse = p->pParse;
1731   Window *pMWin = p->pMWin;
1732   Vdbe *v = sqlite3GetVdbe(pParse);
1733   Window *pWin;
1734 
1735   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1736     if( pMWin->regStartRowid==0
1737      && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1738      && (pWin->eStart!=TK_UNBOUNDED)
1739     ){
1740       sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1741       sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
1742       VdbeCoverage(v);
1743       sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
1744       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1745     }else if( pWin->regApp ){
1746       assert( pMWin->regStartRowid==0 );
1747     }else{
1748       int nArg = windowArgCount(pWin);
1749       if( bFin ){
1750         sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
1751         sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
1752         sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
1753         sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1754       }else{
1755         sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
1756         sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
1757       }
1758     }
1759   }
1760 }
1761 
1762 /*
1763 ** Generate code to calculate the current values of all window functions in the
1764 ** p->pMWin list by doing a full scan of the current window frame. Store the
1765 ** results in the Window.regResult registers, ready to return the upper
1766 ** layer.
1767 */
1768 static void windowFullScan(WindowCodeArg *p){
1769   Window *pWin;
1770   Parse *pParse = p->pParse;
1771   Window *pMWin = p->pMWin;
1772   Vdbe *v = p->pVdbe;
1773 
1774   int regCRowid = 0;              /* Current rowid value */
1775   int regCPeer = 0;               /* Current peer values */
1776   int regRowid = 0;               /* AggStep rowid value */
1777   int regPeer = 0;                /* AggStep peer values */
1778 
1779   int nPeer;
1780   int lblNext;
1781   int lblBrk;
1782   int addrNext;
1783   int csr;
1784 
1785   VdbeModuleComment((v, "windowFullScan begin"));
1786 
1787   assert( pMWin!=0 );
1788   csr = pMWin->csrApp;
1789   nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
1790 
1791   lblNext = sqlite3VdbeMakeLabel(pParse);
1792   lblBrk = sqlite3VdbeMakeLabel(pParse);
1793 
1794   regCRowid = sqlite3GetTempReg(pParse);
1795   regRowid = sqlite3GetTempReg(pParse);
1796   if( nPeer ){
1797     regCPeer = sqlite3GetTempRange(pParse, nPeer);
1798     regPeer = sqlite3GetTempRange(pParse, nPeer);
1799   }
1800 
1801   sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
1802   windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
1803 
1804   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1805     sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1806   }
1807 
1808   sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
1809   VdbeCoverage(v);
1810   addrNext = sqlite3VdbeCurrentAddr(v);
1811   sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);
1812   sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
1813   VdbeCoverageNeverNull(v);
1814 
1815   if( pMWin->eExclude==TK_CURRENT ){
1816     sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);
1817     VdbeCoverageNeverNull(v);
1818   }else if( pMWin->eExclude!=TK_NO ){
1819     int addr;
1820     int addrEq = 0;
1821     KeyInfo *pKeyInfo = 0;
1822 
1823     if( pMWin->pOrderBy ){
1824       pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
1825     }
1826     if( pMWin->eExclude==TK_TIES ){
1827       addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);
1828       VdbeCoverageNeverNull(v);
1829     }
1830     if( pKeyInfo ){
1831       windowReadPeerValues(p, csr, regPeer);
1832       sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);
1833       sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1834       addr = sqlite3VdbeCurrentAddr(v)+1;
1835       sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);
1836       VdbeCoverageEqNe(v);
1837     }else{
1838       sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);
1839     }
1840     if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);
1841   }
1842 
1843   windowAggStep(p, pMWin, csr, 0, p->regArg);
1844 
1845   sqlite3VdbeResolveLabel(v, lblNext);
1846   sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);
1847   VdbeCoverage(v);
1848   sqlite3VdbeJumpHere(v, addrNext-1);
1849   sqlite3VdbeJumpHere(v, addrNext+1);
1850   sqlite3ReleaseTempReg(pParse, regRowid);
1851   sqlite3ReleaseTempReg(pParse, regCRowid);
1852   if( nPeer ){
1853     sqlite3ReleaseTempRange(pParse, regPeer, nPeer);
1854     sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);
1855   }
1856 
1857   windowAggFinal(p, 1);
1858   VdbeModuleComment((v, "windowFullScan end"));
1859 }
1860 
1861 /*
1862 ** Invoke the sub-routine at regGosub (generated by code in select.c) to
1863 ** return the current row of Window.iEphCsr. If all window functions are
1864 ** aggregate window functions that use the standard API, a single
1865 ** OP_Gosub instruction is all that this routine generates. Extra VM code
1866 ** for per-row processing is only generated for the following built-in window
1867 ** functions:
1868 **
1869 **   nth_value()
1870 **   first_value()
1871 **   lag()
1872 **   lead()
1873 */
1874 static void windowReturnOneRow(WindowCodeArg *p){
1875   Window *pMWin = p->pMWin;
1876   Vdbe *v = p->pVdbe;
1877 
1878   if( pMWin->regStartRowid ){
1879     windowFullScan(p);
1880   }else{
1881     Parse *pParse = p->pParse;
1882     Window *pWin;
1883 
1884     for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1885       FuncDef *pFunc = pWin->pFunc;
1886       if( pFunc->zName==nth_valueName
1887        || pFunc->zName==first_valueName
1888       ){
1889         int csr = pWin->csrApp;
1890         int lbl = sqlite3VdbeMakeLabel(pParse);
1891         int tmpReg = sqlite3GetTempReg(pParse);
1892         sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1893 
1894         if( pFunc->zName==nth_valueName ){
1895           sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
1896           windowCheckValue(pParse, tmpReg, 2);
1897         }else{
1898           sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
1899         }
1900         sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
1901         sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
1902         VdbeCoverageNeverNull(v);
1903         sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
1904         VdbeCoverageNeverTaken(v);
1905         sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1906         sqlite3VdbeResolveLabel(v, lbl);
1907         sqlite3ReleaseTempReg(pParse, tmpReg);
1908       }
1909       else if( pFunc->zName==leadName || pFunc->zName==lagName ){
1910         int nArg = pWin->pOwner->x.pList->nExpr;
1911         int csr = pWin->csrApp;
1912         int lbl = sqlite3VdbeMakeLabel(pParse);
1913         int tmpReg = sqlite3GetTempReg(pParse);
1914         int iEph = pMWin->iEphCsr;
1915 
1916         if( nArg<3 ){
1917           sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1918         }else{
1919           sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
1920         }
1921         sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
1922         if( nArg<2 ){
1923           int val = (pFunc->zName==leadName ? 1 : -1);
1924           sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
1925         }else{
1926           int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
1927           int tmpReg2 = sqlite3GetTempReg(pParse);
1928           sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
1929           sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
1930           sqlite3ReleaseTempReg(pParse, tmpReg2);
1931         }
1932 
1933         sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
1934         VdbeCoverage(v);
1935         sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1936         sqlite3VdbeResolveLabel(v, lbl);
1937         sqlite3ReleaseTempReg(pParse, tmpReg);
1938       }
1939     }
1940   }
1941   sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
1942 }
1943 
1944 /*
1945 ** Generate code to set the accumulator register for each window function
1946 ** in the linked list passed as the second argument to NULL. And perform
1947 ** any equivalent initialization required by any built-in window functions
1948 ** in the list.
1949 */
1950 static int windowInitAccum(Parse *pParse, Window *pMWin){
1951   Vdbe *v = sqlite3GetVdbe(pParse);
1952   int regArg;
1953   int nArg = 0;
1954   Window *pWin;
1955   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1956     FuncDef *pFunc = pWin->pFunc;
1957     assert( pWin->regAccum );
1958     sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1959     nArg = MAX(nArg, windowArgCount(pWin));
1960     if( pMWin->regStartRowid==0 ){
1961       if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
1962         sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
1963         sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1964       }
1965 
1966       if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
1967         assert( pWin->eStart!=TK_UNBOUNDED );
1968         sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
1969         sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1970       }
1971     }
1972   }
1973   regArg = pParse->nMem+1;
1974   pParse->nMem += nArg;
1975   return regArg;
1976 }
1977 
1978 /*
1979 ** Return true if the current frame should be cached in the ephemeral table,
1980 ** even if there are no xInverse() calls required.
1981 */
1982 static int windowCacheFrame(Window *pMWin){
1983   Window *pWin;
1984   if( pMWin->regStartRowid ) return 1;
1985   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1986     FuncDef *pFunc = pWin->pFunc;
1987     if( (pFunc->zName==nth_valueName)
1988      || (pFunc->zName==first_valueName)
1989      || (pFunc->zName==leadName)
1990      || (pFunc->zName==lagName)
1991     ){
1992       return 1;
1993     }
1994   }
1995   return 0;
1996 }
1997 
1998 /*
1999 ** regOld and regNew are each the first register in an array of size
2000 ** pOrderBy->nExpr. This function generates code to compare the two
2001 ** arrays of registers using the collation sequences and other comparison
2002 ** parameters specified by pOrderBy.
2003 **
2004 ** If the two arrays are not equal, the contents of regNew is copied to
2005 ** regOld and control falls through. Otherwise, if the contents of the arrays
2006 ** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
2007 */
2008 static void windowIfNewPeer(
2009   Parse *pParse,
2010   ExprList *pOrderBy,
2011   int regNew,                     /* First in array of new values */
2012   int regOld,                     /* First in array of old values */
2013   int addr                        /* Jump here */
2014 ){
2015   Vdbe *v = sqlite3GetVdbe(pParse);
2016   if( pOrderBy ){
2017     int nVal = pOrderBy->nExpr;
2018     KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
2019     sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
2020     sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
2021     sqlite3VdbeAddOp3(v, OP_Jump,
2022       sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
2023     );
2024     VdbeCoverageEqNe(v);
2025     sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
2026   }else{
2027     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
2028   }
2029 }
2030 
2031 /*
2032 ** This function is called as part of generating VM programs for RANGE
2033 ** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
2034 ** the ORDER BY term in the window, and that argument op is OP_Ge, it generates
2035 ** code equivalent to:
2036 **
2037 **   if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
2038 **
2039 ** The value of parameter op may also be OP_Gt or OP_Le. In these cases the
2040 ** operator in the above pseudo-code is replaced with ">" or "<=", respectively.
2041 **
2042 ** If the sort-order for the ORDER BY term in the window is DESC, then the
2043 ** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is
2044 ** subtracted. And the comparison operator is inverted to - ">=" becomes "<=",
2045 ** ">" becomes "<", and so on. So, with DESC sort order, if the argument op
2046 ** is OP_Ge, the generated code is equivalent to:
2047 **
2048 **   if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;
2049 **
2050 ** A special type of arithmetic is used such that if csr1.peerVal is not
2051 ** a numeric type (real or integer), then the result of the addition
2052 ** or subtraction is a a copy of csr1.peerVal.
2053 */
2054 static void windowCodeRangeTest(
2055   WindowCodeArg *p,
2056   int op,                         /* OP_Ge, OP_Gt, or OP_Le */
2057   int csr1,                       /* Cursor number for cursor 1 */
2058   int regVal,                     /* Register containing non-negative number */
2059   int csr2,                       /* Cursor number for cursor 2 */
2060   int lbl                         /* Jump destination if condition is true */
2061 ){
2062   Parse *pParse = p->pParse;
2063   Vdbe *v = sqlite3GetVdbe(pParse);
2064   ExprList *pOrderBy = p->pMWin->pOrderBy;  /* ORDER BY clause for window */
2065   int reg1 = sqlite3GetTempReg(pParse);     /* Reg. for csr1.peerVal+regVal */
2066   int reg2 = sqlite3GetTempReg(pParse);     /* Reg. for csr2.peerVal */
2067   int regString = ++pParse->nMem;           /* Reg. for constant value '' */
2068   int arith = OP_Add;                       /* OP_Add or OP_Subtract */
2069   int addrGe;                               /* Jump destination */
2070   int addrDone = sqlite3VdbeMakeLabel(pParse);   /* Address past OP_Ge */
2071   CollSeq *pColl;
2072 
2073   /* Read the peer-value from each cursor into a register */
2074   windowReadPeerValues(p, csr1, reg1);
2075   windowReadPeerValues(p, csr2, reg2);
2076 
2077   assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
2078   assert( pOrderBy && pOrderBy->nExpr==1 );
2079   if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_DESC ){
2080     switch( op ){
2081       case OP_Ge: op = OP_Le; break;
2082       case OP_Gt: op = OP_Lt; break;
2083       default: assert( op==OP_Le ); op = OP_Ge; break;
2084     }
2085     arith = OP_Subtract;
2086   }
2087 
2088   VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl",
2089       reg1, (arith==OP_Add ? "+" : "-"), regVal,
2090       ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2
2091   ));
2092 
2093   /* If the BIGNULL flag is set for the ORDER BY, then it is required to
2094   ** consider NULL values to be larger than all other values, instead of
2095   ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this
2096   ** (and adding that capability causes a performance regression), so
2097   ** instead if the BIGNULL flag is set then cases where either reg1 or
2098   ** reg2 are NULL are handled separately in the following block. The code
2099   ** generated is equivalent to:
2100   **
2101   **   if( reg1 IS NULL ){
2102   **     if( op==OP_Ge ) goto lbl;
2103   **     if( op==OP_Gt && reg2 IS NOT NULL ) goto lbl;
2104   **     if( op==OP_Le && reg2 IS NULL ) goto lbl;
2105   **   }else if( reg2 IS NULL ){
2106   **     if( op==OP_Le ) goto lbl;
2107   **   }
2108   **
2109   ** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is
2110   ** not taken, control jumps over the comparison operator coded below this
2111   ** block.  */
2112   if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_BIGNULL ){
2113     /* This block runs if reg1 contains a NULL. */
2114     int addr = sqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v);
2115     switch( op ){
2116       case OP_Ge:
2117         sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl);
2118         break;
2119       case OP_Gt:
2120         sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl);
2121         VdbeCoverage(v);
2122         break;
2123       case OP_Le:
2124         sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl);
2125         VdbeCoverage(v);
2126         break;
2127       default: assert( op==OP_Lt ); /* no-op */ break;
2128     }
2129     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone);
2130 
2131     /* This block runs if reg1 is not NULL, but reg2 is. */
2132     sqlite3VdbeJumpHere(v, addr);
2133     sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); VdbeCoverage(v);
2134     if( op==OP_Gt || op==OP_Ge ){
2135       sqlite3VdbeChangeP2(v, -1, addrDone);
2136     }
2137   }
2138 
2139   /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).
2140   ** This block adds (or subtracts for DESC) the numeric value in regVal
2141   ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob),
2142   ** then leave reg1 as it is. In pseudo-code, this is implemented as:
2143   **
2144   **   if( reg1>='' ) goto addrGe;
2145   **   reg1 = reg1 +/- regVal
2146   **   addrGe:
2147   **
2148   ** Since all strings and blobs are greater-than-or-equal-to an empty string,
2149   ** the add/subtract is skipped for these, as required. If reg1 is a NULL,
2150   ** then the arithmetic is performed, but since adding or subtracting from
2151   ** NULL is always NULL anyway, this case is handled as required too.  */
2152   sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
2153   addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
2154   VdbeCoverage(v);
2155   if( (op==OP_Ge && arith==OP_Add) || (op==OP_Le && arith==OP_Subtract) ){
2156     sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
2157   }
2158   sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
2159   sqlite3VdbeJumpHere(v, addrGe);
2160 
2161   /* Compare registers reg2 and reg1, taking the jump if required. Note that
2162   ** control skips over this test if the BIGNULL flag is set and either
2163   ** reg1 or reg2 contain a NULL value.  */
2164   sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
2165   pColl = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[0].pExpr);
2166   sqlite3VdbeAppendP4(v, (void*)pColl, P4_COLLSEQ);
2167   sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
2168   sqlite3VdbeResolveLabel(v, addrDone);
2169 
2170   assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
2171   testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);
2172   testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt);
2173   testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le);
2174   testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt);
2175   sqlite3ReleaseTempReg(pParse, reg1);
2176   sqlite3ReleaseTempReg(pParse, reg2);
2177 
2178   VdbeModuleComment((v, "CodeRangeTest: end"));
2179 }
2180 
2181 /*
2182 ** Helper function for sqlite3WindowCodeStep(). Each call to this function
2183 ** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
2184 ** operation. Refer to the header comment for sqlite3WindowCodeStep() for
2185 ** details.
2186 */
2187 static int windowCodeOp(
2188  WindowCodeArg *p,                /* Context object */
2189  int op,                          /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
2190  int regCountdown,                /* Register for OP_IfPos countdown */
2191  int jumpOnEof                    /* Jump here if stepped cursor reaches EOF */
2192 ){
2193   int csr, reg;
2194   Parse *pParse = p->pParse;
2195   Window *pMWin = p->pMWin;
2196   int ret = 0;
2197   Vdbe *v = p->pVdbe;
2198   int addrContinue = 0;
2199   int bPeer = (pMWin->eFrmType!=TK_ROWS);
2200 
2201   int lblDone = sqlite3VdbeMakeLabel(pParse);
2202   int addrNextRange = 0;
2203 
2204   /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
2205   ** starts with UNBOUNDED PRECEDING. */
2206   if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
2207     assert( regCountdown==0 && jumpOnEof==0 );
2208     return 0;
2209   }
2210 
2211   if( regCountdown>0 ){
2212     if( pMWin->eFrmType==TK_RANGE ){
2213       addrNextRange = sqlite3VdbeCurrentAddr(v);
2214       assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );
2215       if( op==WINDOW_AGGINVERSE ){
2216         if( pMWin->eStart==TK_FOLLOWING ){
2217           windowCodeRangeTest(
2218               p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
2219           );
2220         }else{
2221           windowCodeRangeTest(
2222               p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
2223           );
2224         }
2225       }else{
2226         windowCodeRangeTest(
2227             p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
2228         );
2229       }
2230     }else{
2231       sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, lblDone, 1);
2232       VdbeCoverage(v);
2233     }
2234   }
2235 
2236   if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
2237     windowAggFinal(p, 0);
2238   }
2239   addrContinue = sqlite3VdbeCurrentAddr(v);
2240 
2241   /* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or
2242   ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the
2243   ** start cursor does not advance past the end cursor within the
2244   ** temporary table. It otherwise might, if (a>b).  */
2245   if( pMWin->eStart==pMWin->eEnd && regCountdown
2246    && pMWin->eFrmType==TK_RANGE && op==WINDOW_AGGINVERSE
2247   ){
2248     int regRowid1 = sqlite3GetTempReg(pParse);
2249     int regRowid2 = sqlite3GetTempReg(pParse);
2250     sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1);
2251     sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2);
2252     sqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1);
2253     VdbeCoverage(v);
2254     sqlite3ReleaseTempReg(pParse, regRowid1);
2255     sqlite3ReleaseTempReg(pParse, regRowid2);
2256     assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING );
2257   }
2258 
2259   switch( op ){
2260     case WINDOW_RETURN_ROW:
2261       csr = p->current.csr;
2262       reg = p->current.reg;
2263       windowReturnOneRow(p);
2264       break;
2265 
2266     case WINDOW_AGGINVERSE:
2267       csr = p->start.csr;
2268       reg = p->start.reg;
2269       if( pMWin->regStartRowid ){
2270         assert( pMWin->regEndRowid );
2271         sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
2272       }else{
2273         windowAggStep(p, pMWin, csr, 1, p->regArg);
2274       }
2275       break;
2276 
2277     default:
2278       assert( op==WINDOW_AGGSTEP );
2279       csr = p->end.csr;
2280       reg = p->end.reg;
2281       if( pMWin->regStartRowid ){
2282         assert( pMWin->regEndRowid );
2283         sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
2284       }else{
2285         windowAggStep(p, pMWin, csr, 0, p->regArg);
2286       }
2287       break;
2288   }
2289 
2290   if( op==p->eDelete ){
2291     sqlite3VdbeAddOp1(v, OP_Delete, csr);
2292     sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
2293   }
2294 
2295   if( jumpOnEof ){
2296     sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
2297     VdbeCoverage(v);
2298     ret = sqlite3VdbeAddOp0(v, OP_Goto);
2299   }else{
2300     sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
2301     VdbeCoverage(v);
2302     if( bPeer ){
2303       sqlite3VdbeAddOp2(v, OP_Goto, 0, lblDone);
2304     }
2305   }
2306 
2307   if( bPeer ){
2308     int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
2309     int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
2310     windowReadPeerValues(p, csr, regTmp);
2311     windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
2312     sqlite3ReleaseTempRange(pParse, regTmp, nReg);
2313   }
2314 
2315   if( addrNextRange ){
2316     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
2317   }
2318   sqlite3VdbeResolveLabel(v, lblDone);
2319   return ret;
2320 }
2321 
2322 
2323 /*
2324 ** Allocate and return a duplicate of the Window object indicated by the
2325 ** third argument. Set the Window.pOwner field of the new object to
2326 ** pOwner.
2327 */
2328 Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
2329   Window *pNew = 0;
2330   if( ALWAYS(p) ){
2331     pNew = sqlite3DbMallocZero(db, sizeof(Window));
2332     if( pNew ){
2333       pNew->zName = sqlite3DbStrDup(db, p->zName);
2334       pNew->zBase = sqlite3DbStrDup(db, p->zBase);
2335       pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
2336       pNew->pFunc = p->pFunc;
2337       pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
2338       pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
2339       pNew->eFrmType = p->eFrmType;
2340       pNew->eEnd = p->eEnd;
2341       pNew->eStart = p->eStart;
2342       pNew->eExclude = p->eExclude;
2343       pNew->regResult = p->regResult;
2344       pNew->regAccum = p->regAccum;
2345       pNew->iArgCol = p->iArgCol;
2346       pNew->iEphCsr = p->iEphCsr;
2347       pNew->bExprArgs = p->bExprArgs;
2348       pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
2349       pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
2350       pNew->pOwner = pOwner;
2351       pNew->bImplicitFrame = p->bImplicitFrame;
2352     }
2353   }
2354   return pNew;
2355 }
2356 
2357 /*
2358 ** Return a copy of the linked list of Window objects passed as the
2359 ** second argument.
2360 */
2361 Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
2362   Window *pWin;
2363   Window *pRet = 0;
2364   Window **pp = &pRet;
2365 
2366   for(pWin=p; pWin; pWin=pWin->pNextWin){
2367     *pp = sqlite3WindowDup(db, 0, pWin);
2368     if( *pp==0 ) break;
2369     pp = &((*pp)->pNextWin);
2370   }
2371 
2372   return pRet;
2373 }
2374 
2375 /*
2376 ** Return true if it can be determined at compile time that expression
2377 ** pExpr evaluates to a value that, when cast to an integer, is greater
2378 ** than zero. False otherwise.
2379 **
2380 ** If an OOM error occurs, this function sets the Parse.db.mallocFailed
2381 ** flag and returns zero.
2382 */
2383 static int windowExprGtZero(Parse *pParse, Expr *pExpr){
2384   int ret = 0;
2385   sqlite3 *db = pParse->db;
2386   sqlite3_value *pVal = 0;
2387   sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);
2388   if( pVal && sqlite3_value_int(pVal)>0 ){
2389     ret = 1;
2390   }
2391   sqlite3ValueFree(pVal);
2392   return ret;
2393 }
2394 
2395 /*
2396 ** sqlite3WhereBegin() has already been called for the SELECT statement
2397 ** passed as the second argument when this function is invoked. It generates
2398 ** code to populate the Window.regResult register for each window function
2399 ** and invoke the sub-routine at instruction addrGosub once for each row.
2400 ** sqlite3WhereEnd() is always called before returning.
2401 **
2402 ** This function handles several different types of window frames, which
2403 ** require slightly different processing. The following pseudo code is
2404 ** used to implement window frames of the form:
2405 **
2406 **   ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
2407 **
2408 ** Other window frame types use variants of the following:
2409 **
2410 **     ... loop started by sqlite3WhereBegin() ...
2411 **       if( new partition ){
2412 **         Gosub flush
2413 **       }
2414 **       Insert new row into eph table.
2415 **
2416 **       if( first row of partition ){
2417 **         // Rewind three cursors, all open on the eph table.
2418 **         Rewind(csrEnd);
2419 **         Rewind(csrStart);
2420 **         Rewind(csrCurrent);
2421 **
2422 **         regEnd = <expr2>          // FOLLOWING expression
2423 **         regStart = <expr1>        // PRECEDING expression
2424 **       }else{
2425 **         // First time this branch is taken, the eph table contains two
2426 **         // rows. The first row in the partition, which all three cursors
2427 **         // currently point to, and the following row.
2428 **         AGGSTEP
2429 **         if( (regEnd--)<=0 ){
2430 **           RETURN_ROW
2431 **           if( (regStart--)<=0 ){
2432 **             AGGINVERSE
2433 **           }
2434 **         }
2435 **       }
2436 **     }
2437 **     flush:
2438 **       AGGSTEP
2439 **       while( 1 ){
2440 **         RETURN ROW
2441 **         if( csrCurrent is EOF ) break;
2442 **         if( (regStart--)<=0 ){
2443 **           AggInverse(csrStart)
2444 **           Next(csrStart)
2445 **         }
2446 **       }
2447 **
2448 ** The pseudo-code above uses the following shorthand:
2449 **
2450 **   AGGSTEP:    invoke the aggregate xStep() function for each window function
2451 **               with arguments read from the current row of cursor csrEnd, then
2452 **               step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
2453 **
2454 **   RETURN_ROW: return a row to the caller based on the contents of the
2455 **               current row of csrCurrent and the current state of all
2456 **               aggregates. Then step cursor csrCurrent forward one row.
2457 **
2458 **   AGGINVERSE: invoke the aggregate xInverse() function for each window
2459 **               functions with arguments read from the current row of cursor
2460 **               csrStart. Then step csrStart forward one row.
2461 **
2462 ** There are two other ROWS window frames that are handled significantly
2463 ** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
2464 ** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
2465 ** cases because they change the order in which the three cursors (csrStart,
2466 ** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
2467 ** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
2468 ** three.
2469 **
2470 **   ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2471 **
2472 **     ... loop started by sqlite3WhereBegin() ...
2473 **       if( new partition ){
2474 **         Gosub flush
2475 **       }
2476 **       Insert new row into eph table.
2477 **       if( first row of partition ){
2478 **         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2479 **         regEnd = <expr2>
2480 **         regStart = <expr1>
2481 **       }else{
2482 **         if( (regEnd--)<=0 ){
2483 **           AGGSTEP
2484 **         }
2485 **         RETURN_ROW
2486 **         if( (regStart--)<=0 ){
2487 **           AGGINVERSE
2488 **         }
2489 **       }
2490 **     }
2491 **     flush:
2492 **       if( (regEnd--)<=0 ){
2493 **         AGGSTEP
2494 **       }
2495 **       RETURN_ROW
2496 **
2497 **
2498 **   ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2499 **
2500 **     ... loop started by sqlite3WhereBegin() ...
2501 **     if( new partition ){
2502 **       Gosub flush
2503 **     }
2504 **     Insert new row into eph table.
2505 **     if( first row of partition ){
2506 **       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2507 **       regEnd = <expr2>
2508 **       regStart = regEnd - <expr1>
2509 **     }else{
2510 **       AGGSTEP
2511 **       if( (regEnd--)<=0 ){
2512 **         RETURN_ROW
2513 **       }
2514 **       if( (regStart--)<=0 ){
2515 **         AGGINVERSE
2516 **       }
2517 **     }
2518 **   }
2519 **   flush:
2520 **     AGGSTEP
2521 **     while( 1 ){
2522 **       if( (regEnd--)<=0 ){
2523 **         RETURN_ROW
2524 **         if( eof ) break;
2525 **       }
2526 **       if( (regStart--)<=0 ){
2527 **         AGGINVERSE
2528 **         if( eof ) break
2529 **       }
2530 **     }
2531 **     while( !eof csrCurrent ){
2532 **       RETURN_ROW
2533 **     }
2534 **
2535 ** For the most part, the patterns above are adapted to support UNBOUNDED by
2536 ** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
2537 ** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING".
2538 ** This is optimized of course - branches that will never be taken and
2539 ** conditions that are always true are omitted from the VM code. The only
2540 ** exceptional case is:
2541 **
2542 **   ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
2543 **
2544 **     ... loop started by sqlite3WhereBegin() ...
2545 **     if( new partition ){
2546 **       Gosub flush
2547 **     }
2548 **     Insert new row into eph table.
2549 **     if( first row of partition ){
2550 **       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2551 **       regStart = <expr1>
2552 **     }else{
2553 **       AGGSTEP
2554 **     }
2555 **   }
2556 **   flush:
2557 **     AGGSTEP
2558 **     while( 1 ){
2559 **       if( (regStart--)<=0 ){
2560 **         AGGINVERSE
2561 **         if( eof ) break
2562 **       }
2563 **       RETURN_ROW
2564 **     }
2565 **     while( !eof csrCurrent ){
2566 **       RETURN_ROW
2567 **     }
2568 **
2569 ** Also requiring special handling are the cases:
2570 **
2571 **   ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2572 **   ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2573 **
2574 ** when (expr1 < expr2). This is detected at runtime, not by this function.
2575 ** To handle this case, the pseudo-code programs depicted above are modified
2576 ** slightly to be:
2577 **
2578 **     ... loop started by sqlite3WhereBegin() ...
2579 **     if( new partition ){
2580 **       Gosub flush
2581 **     }
2582 **     Insert new row into eph table.
2583 **     if( first row of partition ){
2584 **       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2585 **       regEnd = <expr2>
2586 **       regStart = <expr1>
2587 **       if( regEnd < regStart ){
2588 **         RETURN_ROW
2589 **         delete eph table contents
2590 **         continue
2591 **       }
2592 **     ...
2593 **
2594 ** The new "continue" statement in the above jumps to the next iteration
2595 ** of the outer loop - the one started by sqlite3WhereBegin().
2596 **
2597 ** The various GROUPS cases are implemented using the same patterns as
2598 ** ROWS. The VM code is modified slightly so that:
2599 **
2600 **   1. The else branch in the main loop is only taken if the row just
2601 **      added to the ephemeral table is the start of a new group. In
2602 **      other words, it becomes:
2603 **
2604 **         ... loop started by sqlite3WhereBegin() ...
2605 **         if( new partition ){
2606 **           Gosub flush
2607 **         }
2608 **         Insert new row into eph table.
2609 **         if( first row of partition ){
2610 **           Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2611 **           regEnd = <expr2>
2612 **           regStart = <expr1>
2613 **         }else if( new group ){
2614 **           ...
2615 **         }
2616 **       }
2617 **
2618 **   2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
2619 **      AGGINVERSE step processes the current row of the relevant cursor and
2620 **      all subsequent rows belonging to the same group.
2621 **
2622 ** RANGE window frames are a little different again. As for GROUPS, the
2623 ** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
2624 ** deal in groups instead of rows. As for ROWS and GROUPS, there are three
2625 ** basic cases:
2626 **
2627 **   RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
2628 **
2629 **     ... loop started by sqlite3WhereBegin() ...
2630 **       if( new partition ){
2631 **         Gosub flush
2632 **       }
2633 **       Insert new row into eph table.
2634 **       if( first row of partition ){
2635 **         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2636 **         regEnd = <expr2>
2637 **         regStart = <expr1>
2638 **       }else{
2639 **         AGGSTEP
2640 **         while( (csrCurrent.key + regEnd) < csrEnd.key ){
2641 **           RETURN_ROW
2642 **           while( csrStart.key + regStart) < csrCurrent.key ){
2643 **             AGGINVERSE
2644 **           }
2645 **         }
2646 **       }
2647 **     }
2648 **     flush:
2649 **       AGGSTEP
2650 **       while( 1 ){
2651 **         RETURN ROW
2652 **         if( csrCurrent is EOF ) break;
2653 **           while( csrStart.key + regStart) < csrCurrent.key ){
2654 **             AGGINVERSE
2655 **           }
2656 **         }
2657 **       }
2658 **
2659 ** In the above notation, "csr.key" means the current value of the ORDER BY
2660 ** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
2661 ** or <expr PRECEDING) read from cursor csr.
2662 **
2663 **   RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2664 **
2665 **     ... loop started by sqlite3WhereBegin() ...
2666 **       if( new partition ){
2667 **         Gosub flush
2668 **       }
2669 **       Insert new row into eph table.
2670 **       if( first row of partition ){
2671 **         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2672 **         regEnd = <expr2>
2673 **         regStart = <expr1>
2674 **       }else{
2675 **         while( (csrEnd.key + regEnd) <= csrCurrent.key ){
2676 **           AGGSTEP
2677 **         }
2678 **         while( (csrStart.key + regStart) < csrCurrent.key ){
2679 **           AGGINVERSE
2680 **         }
2681 **         RETURN_ROW
2682 **       }
2683 **     }
2684 **     flush:
2685 **       while( (csrEnd.key + regEnd) <= csrCurrent.key ){
2686 **         AGGSTEP
2687 **       }
2688 **       while( (csrStart.key + regStart) < csrCurrent.key ){
2689 **         AGGINVERSE
2690 **       }
2691 **       RETURN_ROW
2692 **
2693 **   RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2694 **
2695 **     ... loop started by sqlite3WhereBegin() ...
2696 **       if( new partition ){
2697 **         Gosub flush
2698 **       }
2699 **       Insert new row into eph table.
2700 **       if( first row of partition ){
2701 **         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2702 **         regEnd = <expr2>
2703 **         regStart = <expr1>
2704 **       }else{
2705 **         AGGSTEP
2706 **         while( (csrCurrent.key + regEnd) < csrEnd.key ){
2707 **           while( (csrCurrent.key + regStart) > csrStart.key ){
2708 **             AGGINVERSE
2709 **           }
2710 **           RETURN_ROW
2711 **         }
2712 **       }
2713 **     }
2714 **     flush:
2715 **       AGGSTEP
2716 **       while( 1 ){
2717 **         while( (csrCurrent.key + regStart) > csrStart.key ){
2718 **           AGGINVERSE
2719 **           if( eof ) break "while( 1 )" loop.
2720 **         }
2721 **         RETURN_ROW
2722 **       }
2723 **       while( !eof csrCurrent ){
2724 **         RETURN_ROW
2725 **       }
2726 **
2727 ** The text above leaves out many details. Refer to the code and comments
2728 ** below for a more complete picture.
2729 */
2730 void sqlite3WindowCodeStep(
2731   Parse *pParse,                  /* Parse context */
2732   Select *p,                      /* Rewritten SELECT statement */
2733   WhereInfo *pWInfo,              /* Context returned by sqlite3WhereBegin() */
2734   int regGosub,                   /* Register for OP_Gosub */
2735   int addrGosub                   /* OP_Gosub here to return each row */
2736 ){
2737   Window *pMWin = p->pWin;
2738   ExprList *pOrderBy = pMWin->pOrderBy;
2739   Vdbe *v = sqlite3GetVdbe(pParse);
2740   int csrWrite;                   /* Cursor used to write to eph. table */
2741   int csrInput = p->pSrc->a[0].iCursor;     /* Cursor of sub-select */
2742   int nInput = p->pSrc->a[0].pTab->nCol;    /* Number of cols returned by sub */
2743   int iInput;                               /* To iterate through sub cols */
2744   int addrNe;                     /* Address of OP_Ne */
2745   int addrGosubFlush = 0;         /* Address of OP_Gosub to flush: */
2746   int addrInteger = 0;            /* Address of OP_Integer */
2747   int addrEmpty;                  /* Address of OP_Rewind in flush: */
2748   int regNew;                     /* Array of registers holding new input row */
2749   int regRecord;                  /* regNew array in record form */
2750   int regRowid;                   /* Rowid for regRecord in eph table */
2751   int regNewPeer = 0;             /* Peer values for new row (part of regNew) */
2752   int regPeer = 0;                /* Peer values for current row */
2753   int regFlushPart = 0;           /* Register for "Gosub flush_partition" */
2754   WindowCodeArg s;                /* Context object for sub-routines */
2755   int lblWhereEnd;                /* Label just before sqlite3WhereEnd() code */
2756   int regStart = 0;               /* Value of <expr> PRECEDING */
2757   int regEnd = 0;                 /* Value of <expr> FOLLOWING */
2758 
2759   assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
2760        || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
2761   );
2762   assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
2763        || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
2764   );
2765   assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
2766        || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
2767        || pMWin->eExclude==TK_NO
2768   );
2769 
2770   lblWhereEnd = sqlite3VdbeMakeLabel(pParse);
2771 
2772   /* Fill in the context object */
2773   memset(&s, 0, sizeof(WindowCodeArg));
2774   s.pParse = pParse;
2775   s.pMWin = pMWin;
2776   s.pVdbe = v;
2777   s.regGosub = regGosub;
2778   s.addrGosub = addrGosub;
2779   s.current.csr = pMWin->iEphCsr;
2780   csrWrite = s.current.csr+1;
2781   s.start.csr = s.current.csr+2;
2782   s.end.csr = s.current.csr+3;
2783 
2784   /* Figure out when rows may be deleted from the ephemeral table. There
2785   ** are four options - they may never be deleted (eDelete==0), they may
2786   ** be deleted as soon as they are no longer part of the window frame
2787   ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
2788   ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
2789   ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
2790   switch( pMWin->eStart ){
2791     case TK_FOLLOWING:
2792       if( pMWin->eFrmType!=TK_RANGE
2793        && windowExprGtZero(pParse, pMWin->pStart)
2794       ){
2795         s.eDelete = WINDOW_RETURN_ROW;
2796       }
2797       break;
2798     case TK_UNBOUNDED:
2799       if( windowCacheFrame(pMWin)==0 ){
2800         if( pMWin->eEnd==TK_PRECEDING ){
2801           if( pMWin->eFrmType!=TK_RANGE
2802            && windowExprGtZero(pParse, pMWin->pEnd)
2803           ){
2804             s.eDelete = WINDOW_AGGSTEP;
2805           }
2806         }else{
2807           s.eDelete = WINDOW_RETURN_ROW;
2808         }
2809       }
2810       break;
2811     default:
2812       s.eDelete = WINDOW_AGGINVERSE;
2813       break;
2814   }
2815 
2816   /* Allocate registers for the array of values from the sub-query, the
2817   ** samve values in record form, and the rowid used to insert said record
2818   ** into the ephemeral table.  */
2819   regNew = pParse->nMem+1;
2820   pParse->nMem += nInput;
2821   regRecord = ++pParse->nMem;
2822   regRowid = ++pParse->nMem;
2823 
2824   /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
2825   ** clause, allocate registers to store the results of evaluating each
2826   ** <expr>.  */
2827   if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
2828     regStart = ++pParse->nMem;
2829   }
2830   if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
2831     regEnd = ++pParse->nMem;
2832   }
2833 
2834   /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
2835   ** registers to store copies of the ORDER BY expressions (peer values)
2836   ** for the main loop, and for each cursor (start, current and end). */
2837   if( pMWin->eFrmType!=TK_ROWS ){
2838     int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
2839     regNewPeer = regNew + pMWin->nBufferCol;
2840     if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
2841     regPeer = pParse->nMem+1;       pParse->nMem += nPeer;
2842     s.start.reg = pParse->nMem+1;   pParse->nMem += nPeer;
2843     s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
2844     s.end.reg = pParse->nMem+1;     pParse->nMem += nPeer;
2845   }
2846 
2847   /* Load the column values for the row returned by the sub-select
2848   ** into an array of registers starting at regNew. Assemble them into
2849   ** a record in register regRecord. */
2850   for(iInput=0; iInput<nInput; iInput++){
2851     sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
2852   }
2853   sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
2854 
2855   /* An input row has just been read into an array of registers starting
2856   ** at regNew. If the window has a PARTITION clause, this block generates
2857   ** VM code to check if the input row is the start of a new partition.
2858   ** If so, it does an OP_Gosub to an address to be filled in later. The
2859   ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
2860   if( pMWin->pPartition ){
2861     int addr;
2862     ExprList *pPart = pMWin->pPartition;
2863     int nPart = pPart->nExpr;
2864     int regNewPart = regNew + pMWin->nBufferCol;
2865     KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
2866 
2867     regFlushPart = ++pParse->nMem;
2868     addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
2869     sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
2870     sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
2871     VdbeCoverageEqNe(v);
2872     addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
2873     VdbeComment((v, "call flush_partition"));
2874     sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
2875   }
2876 
2877   /* Insert the new row into the ephemeral table */
2878   sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid);
2879   sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid);
2880   addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid);
2881   VdbeCoverageNeverNull(v);
2882 
2883   /* This block is run for the first row of each partition */
2884   s.regArg = windowInitAccum(pParse, pMWin);
2885 
2886   if( regStart ){
2887     sqlite3ExprCode(pParse, pMWin->pStart, regStart);
2888     windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE?3:0));
2889   }
2890   if( regEnd ){
2891     sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
2892     windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE?3:0));
2893   }
2894 
2895   if( pMWin->eFrmType!=TK_RANGE && pMWin->eStart==pMWin->eEnd && regStart ){
2896     int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
2897     int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
2898     VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */
2899     VdbeCoverageNeverNullIf(v, op==OP_Le); /*   values previously checked */
2900     windowAggFinal(&s, 0);
2901     sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
2902     VdbeCoverageNeverTaken(v);
2903     windowReturnOneRow(&s);
2904     sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
2905     sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
2906     sqlite3VdbeJumpHere(v, addrGe);
2907   }
2908   if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){
2909     assert( pMWin->eEnd==TK_FOLLOWING );
2910     sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
2911   }
2912 
2913   if( pMWin->eStart!=TK_UNBOUNDED ){
2914     sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1);
2915     VdbeCoverageNeverTaken(v);
2916   }
2917   sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
2918   VdbeCoverageNeverTaken(v);
2919   sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1);
2920   VdbeCoverageNeverTaken(v);
2921   if( regPeer && pOrderBy ){
2922     sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
2923     sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
2924     sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
2925     sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
2926   }
2927 
2928   sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
2929 
2930   sqlite3VdbeJumpHere(v, addrNe);
2931 
2932   /* Beginning of the block executed for the second and subsequent rows. */
2933   if( regPeer ){
2934     windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);
2935   }
2936   if( pMWin->eStart==TK_FOLLOWING ){
2937     windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
2938     if( pMWin->eEnd!=TK_UNBOUNDED ){
2939       if( pMWin->eFrmType==TK_RANGE ){
2940         int lbl = sqlite3VdbeMakeLabel(pParse);
2941         int addrNext = sqlite3VdbeCurrentAddr(v);
2942         windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2943         windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2944         windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2945         sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
2946         sqlite3VdbeResolveLabel(v, lbl);
2947       }else{
2948         windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
2949         windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2950       }
2951     }
2952   }else
2953   if( pMWin->eEnd==TK_PRECEDING ){
2954     int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
2955     windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
2956     if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2957     windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2958     if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2959   }else{
2960     int addr = 0;
2961     windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
2962     if( pMWin->eEnd!=TK_UNBOUNDED ){
2963       if( pMWin->eFrmType==TK_RANGE ){
2964         int lbl = 0;
2965         addr = sqlite3VdbeCurrentAddr(v);
2966         if( regEnd ){
2967           lbl = sqlite3VdbeMakeLabel(pParse);
2968           windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2969         }
2970         windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2971         windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2972         if( regEnd ){
2973           sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
2974           sqlite3VdbeResolveLabel(v, lbl);
2975         }
2976       }else{
2977         if( regEnd ){
2978           addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
2979           VdbeCoverage(v);
2980         }
2981         windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2982         windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2983         if( regEnd ) sqlite3VdbeJumpHere(v, addr);
2984       }
2985     }
2986   }
2987 
2988   /* End of the main input loop */
2989   sqlite3VdbeResolveLabel(v, lblWhereEnd);
2990   sqlite3WhereEnd(pWInfo);
2991 
2992   /* Fall through */
2993   if( pMWin->pPartition ){
2994     addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
2995     sqlite3VdbeJumpHere(v, addrGosubFlush);
2996   }
2997 
2998   addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
2999   VdbeCoverage(v);
3000   if( pMWin->eEnd==TK_PRECEDING ){
3001     int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
3002     windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
3003     if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
3004     windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
3005   }else if( pMWin->eStart==TK_FOLLOWING ){
3006     int addrStart;
3007     int addrBreak1;
3008     int addrBreak2;
3009     int addrBreak3;
3010     windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
3011     if( pMWin->eFrmType==TK_RANGE ){
3012       addrStart = sqlite3VdbeCurrentAddr(v);
3013       addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
3014       addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
3015     }else
3016     if( pMWin->eEnd==TK_UNBOUNDED ){
3017       addrStart = sqlite3VdbeCurrentAddr(v);
3018       addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
3019       addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
3020     }else{
3021       assert( pMWin->eEnd==TK_FOLLOWING );
3022       addrStart = sqlite3VdbeCurrentAddr(v);
3023       addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
3024       addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
3025     }
3026     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
3027     sqlite3VdbeJumpHere(v, addrBreak2);
3028     addrStart = sqlite3VdbeCurrentAddr(v);
3029     addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
3030     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
3031     sqlite3VdbeJumpHere(v, addrBreak1);
3032     sqlite3VdbeJumpHere(v, addrBreak3);
3033   }else{
3034     int addrBreak;
3035     int addrStart;
3036     windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
3037     addrStart = sqlite3VdbeCurrentAddr(v);
3038     addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
3039     windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
3040     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
3041     sqlite3VdbeJumpHere(v, addrBreak);
3042   }
3043   sqlite3VdbeJumpHere(v, addrEmpty);
3044 
3045   sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
3046   if( pMWin->pPartition ){
3047     if( pMWin->regStartRowid ){
3048       sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
3049       sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
3050     }
3051     sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
3052     sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
3053   }
3054 }
3055 
3056 #endif /* SQLITE_OMIT_WINDOWFUNC */
3057