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