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