xref: /sqlite-3.40.0/src/window.c (revision f71a243a)
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 ){
938       if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
939         sqlite3ExprListDelete(db, p->pOrderBy);
940         p->pOrderBy = 0;
941       }
942     }
943 
944     /* Assign a cursor number for the ephemeral table used to buffer rows.
945     ** The OpenEphemeral instruction is coded later, after it is known how
946     ** many columns the table will have.  */
947     pMWin->iEphCsr = pParse->nTab++;
948     pParse->nTab += 3;
949 
950     selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);
951     selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);
952     pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
953 
954     /* Append the PARTITION BY and ORDER BY expressions to the to the
955     ** sub-select expression list. They are required to figure out where
956     ** boundaries for partitions and sets of peer rows lie.  */
957     pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);
958     pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);
959 
960     /* Append the arguments passed to each window function to the
961     ** sub-select expression list. Also allocate two registers for each
962     ** window function - one for the accumulator, another for interim
963     ** results.  */
964     for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
965       pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
966       pSublist = exprListAppendList(pParse, pSublist, pWin->pOwner->x.pList, 0);
967       if( pWin->pFilter ){
968         Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
969         pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
970       }
971       pWin->regAccum = ++pParse->nMem;
972       pWin->regResult = ++pParse->nMem;
973       sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
974     }
975 
976     /* If there is no ORDER BY or PARTITION BY clause, and the window
977     ** function accepts zero arguments, and there are no other columns
978     ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
979     ** that pSublist is still NULL here. Add a constant expression here to
980     ** keep everything legal in this case.
981     */
982     if( pSublist==0 ){
983       pSublist = sqlite3ExprListAppend(pParse, 0,
984           sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0)
985       );
986     }
987 
988     pSub = sqlite3SelectNew(
989         pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
990     );
991     p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
992     if( p->pSrc ){
993       Table *pTab2;
994       p->pSrc->a[0].pSelect = pSub;
995       sqlite3SrcListAssignCursors(pParse, p->pSrc);
996       pSub->selFlags |= SF_Expanded;
997       pTab2 = sqlite3ResultSetOfSelect(pParse, pSub);
998       if( pTab2==0 ){
999         rc = SQLITE_NOMEM;
1000       }else{
1001         memcpy(pTab, pTab2, sizeof(Table));
1002         pTab->tabFlags |= TF_Ephemeral;
1003         p->pSrc->a[0].pTab = pTab;
1004         pTab = pTab2;
1005       }
1006       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);
1007       sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
1008       sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
1009       sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
1010     }else{
1011       sqlite3SelectDelete(db, pSub);
1012     }
1013     if( db->mallocFailed ) rc = SQLITE_NOMEM;
1014     sqlite3DbFree(db, pTab);
1015   }
1016 
1017   return rc;
1018 }
1019 
1020 /*
1021 ** Unlink the Window object from the Select to which it is attached,
1022 ** if it is attached.
1023 */
1024 void sqlite3WindowUnlinkFromSelect(Window *p){
1025   if( p->ppThis ){
1026     *p->ppThis = p->pNextWin;
1027     if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis;
1028     p->ppThis = 0;
1029   }
1030 }
1031 
1032 /*
1033 ** Free the Window object passed as the second argument.
1034 */
1035 void sqlite3WindowDelete(sqlite3 *db, Window *p){
1036   if( p ){
1037     sqlite3WindowUnlinkFromSelect(p);
1038     sqlite3ExprDelete(db, p->pFilter);
1039     sqlite3ExprListDelete(db, p->pPartition);
1040     sqlite3ExprListDelete(db, p->pOrderBy);
1041     sqlite3ExprDelete(db, p->pEnd);
1042     sqlite3ExprDelete(db, p->pStart);
1043     sqlite3DbFree(db, p->zName);
1044     sqlite3DbFree(db, p->zBase);
1045     sqlite3DbFree(db, p);
1046   }
1047 }
1048 
1049 /*
1050 ** Free the linked list of Window objects starting at the second argument.
1051 */
1052 void sqlite3WindowListDelete(sqlite3 *db, Window *p){
1053   while( p ){
1054     Window *pNext = p->pNextWin;
1055     sqlite3WindowDelete(db, p);
1056     p = pNext;
1057   }
1058 }
1059 
1060 /*
1061 ** The argument expression is an PRECEDING or FOLLOWING offset.  The
1062 ** value should be a non-negative integer.  If the value is not a
1063 ** constant, change it to NULL.  The fact that it is then a non-negative
1064 ** integer will be caught later.  But it is important not to leave
1065 ** variable values in the expression tree.
1066 */
1067 static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
1068   if( 0==sqlite3ExprIsConstant(pExpr) ){
1069     if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
1070     sqlite3ExprDelete(pParse->db, pExpr);
1071     pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
1072   }
1073   return pExpr;
1074 }
1075 
1076 /*
1077 ** Allocate and return a new Window object describing a Window Definition.
1078 */
1079 Window *sqlite3WindowAlloc(
1080   Parse *pParse,    /* Parsing context */
1081   int eType,        /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */
1082   int eStart,       /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
1083   Expr *pStart,     /* Start window size if TK_PRECEDING or FOLLOWING */
1084   int eEnd,         /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
1085   Expr *pEnd,       /* End window size if TK_FOLLOWING or PRECEDING */
1086   u8 eExclude       /* EXCLUDE clause */
1087 ){
1088   Window *pWin = 0;
1089   int bImplicitFrame = 0;
1090 
1091   /* Parser assures the following: */
1092   assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
1093   assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
1094            || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
1095   assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
1096            || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
1097   assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
1098   assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
1099 
1100   if( eType==0 ){
1101     bImplicitFrame = 1;
1102     eType = TK_RANGE;
1103   }
1104 
1105   /* Additionally, the
1106   ** starting boundary type may not occur earlier in the following list than
1107   ** the ending boundary type:
1108   **
1109   **   UNBOUNDED PRECEDING
1110   **   <expr> PRECEDING
1111   **   CURRENT ROW
1112   **   <expr> FOLLOWING
1113   **   UNBOUNDED FOLLOWING
1114   **
1115   ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
1116   ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
1117   ** frame boundary.
1118   */
1119   if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
1120    || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
1121   ){
1122     sqlite3ErrorMsg(pParse, "unsupported frame specification");
1123     goto windowAllocErr;
1124   }
1125 
1126   pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
1127   if( pWin==0 ) goto windowAllocErr;
1128   pWin->eFrmType = eType;
1129   pWin->eStart = eStart;
1130   pWin->eEnd = eEnd;
1131   if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){
1132     eExclude = TK_NO;
1133   }
1134   pWin->eExclude = eExclude;
1135   pWin->bImplicitFrame = bImplicitFrame;
1136   pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
1137   pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
1138   return pWin;
1139 
1140 windowAllocErr:
1141   sqlite3ExprDelete(pParse->db, pEnd);
1142   sqlite3ExprDelete(pParse->db, pStart);
1143   return 0;
1144 }
1145 
1146 /*
1147 ** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
1148 ** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
1149 ** equivalent nul-terminated string.
1150 */
1151 Window *sqlite3WindowAssemble(
1152   Parse *pParse,
1153   Window *pWin,
1154   ExprList *pPartition,
1155   ExprList *pOrderBy,
1156   Token *pBase
1157 ){
1158   if( pWin ){
1159     pWin->pPartition = pPartition;
1160     pWin->pOrderBy = pOrderBy;
1161     if( pBase ){
1162       pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
1163     }
1164   }else{
1165     sqlite3ExprListDelete(pParse->db, pPartition);
1166     sqlite3ExprListDelete(pParse->db, pOrderBy);
1167   }
1168   return pWin;
1169 }
1170 
1171 /*
1172 ** Window *pWin has just been created from a WINDOW clause. Tokne pBase
1173 ** is the base window. Earlier windows from the same WINDOW clause are
1174 ** stored in the linked list starting at pWin->pNextWin. This function
1175 ** either updates *pWin according to the base specification, or else
1176 ** leaves an error in pParse.
1177 */
1178 void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
1179   if( pWin->zBase ){
1180     sqlite3 *db = pParse->db;
1181     Window *pExist = windowFind(pParse, pList, pWin->zBase);
1182     if( pExist ){
1183       const char *zErr = 0;
1184       /* Check for errors */
1185       if( pWin->pPartition ){
1186         zErr = "PARTITION clause";
1187       }else if( pExist->pOrderBy && pWin->pOrderBy ){
1188         zErr = "ORDER BY clause";
1189       }else if( pExist->bImplicitFrame==0 ){
1190         zErr = "frame specification";
1191       }
1192       if( zErr ){
1193         sqlite3ErrorMsg(pParse,
1194             "cannot override %s of window: %s", zErr, pWin->zBase
1195         );
1196       }else{
1197         pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
1198         if( pExist->pOrderBy ){
1199           assert( pWin->pOrderBy==0 );
1200           pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
1201         }
1202         sqlite3DbFree(db, pWin->zBase);
1203         pWin->zBase = 0;
1204       }
1205     }
1206   }
1207 }
1208 
1209 /*
1210 ** Attach window object pWin to expression p.
1211 */
1212 void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
1213   if( p ){
1214     assert( p->op==TK_FUNCTION );
1215     assert( pWin );
1216     p->y.pWin = pWin;
1217     ExprSetProperty(p, EP_WinFunc);
1218     pWin->pOwner = p;
1219     if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){
1220       sqlite3ErrorMsg(pParse,
1221           "DISTINCT is not supported for window functions"
1222       );
1223     }
1224   }else{
1225     sqlite3WindowDelete(pParse->db, pWin);
1226   }
1227 }
1228 
1229 /*
1230 ** Return 0 if the two window objects are identical, or non-zero otherwise.
1231 ** Identical window objects can be processed in a single scan.
1232 */
1233 int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2, int bFilter){
1234   if( p1->eFrmType!=p2->eFrmType ) return 1;
1235   if( p1->eStart!=p2->eStart ) return 1;
1236   if( p1->eEnd!=p2->eEnd ) return 1;
1237   if( p1->eExclude!=p2->eExclude ) return 1;
1238   if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
1239   if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
1240   if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1;
1241   if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1;
1242   if( bFilter ){
1243     if( sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1) ) return 1;
1244   }
1245   return 0;
1246 }
1247 
1248 
1249 /*
1250 ** This is called by code in select.c before it calls sqlite3WhereBegin()
1251 ** to begin iterating through the sub-query results. It is used to allocate
1252 ** and initialize registers and cursors used by sqlite3WindowCodeStep().
1253 */
1254 void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){
1255   Window *pWin;
1256   Vdbe *v = sqlite3GetVdbe(pParse);
1257 
1258   /* Allocate registers to use for PARTITION BY values, if any. Initialize
1259   ** said registers to NULL.  */
1260   if( pMWin->pPartition ){
1261     int nExpr = pMWin->pPartition->nExpr;
1262     pMWin->regPart = pParse->nMem+1;
1263     pParse->nMem += nExpr;
1264     sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
1265   }
1266 
1267   pMWin->regOne = ++pParse->nMem;
1268   sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
1269 
1270   if( pMWin->eExclude ){
1271     pMWin->regStartRowid = ++pParse->nMem;
1272     pMWin->regEndRowid = ++pParse->nMem;
1273     pMWin->csrApp = pParse->nTab++;
1274     sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
1275     sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
1276     sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
1277     return;
1278   }
1279 
1280   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1281     FuncDef *p = pWin->pFunc;
1282     if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
1283       /* The inline versions of min() and max() require a single ephemeral
1284       ** table and 3 registers. The registers are used as follows:
1285       **
1286       **   regApp+0: slot to copy min()/max() argument to for MakeRecord
1287       **   regApp+1: integer value used to ensure keys are unique
1288       **   regApp+2: output of MakeRecord
1289       */
1290       ExprList *pList = pWin->pOwner->x.pList;
1291       KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
1292       pWin->csrApp = pParse->nTab++;
1293       pWin->regApp = pParse->nMem+1;
1294       pParse->nMem += 3;
1295       if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
1296         assert( pKeyInfo->aSortOrder[0]==0 );
1297         pKeyInfo->aSortOrder[0] = 1;
1298       }
1299       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
1300       sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
1301       sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1302     }
1303     else if( p->zName==nth_valueName || p->zName==first_valueName ){
1304       /* Allocate two registers at pWin->regApp. These will be used to
1305       ** store the start and end index of the current frame.  */
1306       pWin->regApp = pParse->nMem+1;
1307       pWin->csrApp = pParse->nTab++;
1308       pParse->nMem += 2;
1309       sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1310     }
1311     else if( p->zName==leadName || p->zName==lagName ){
1312       pWin->csrApp = pParse->nTab++;
1313       sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1314     }
1315   }
1316 }
1317 
1318 #define WINDOW_STARTING_INT  0
1319 #define WINDOW_ENDING_INT    1
1320 #define WINDOW_NTH_VALUE_INT 2
1321 #define WINDOW_STARTING_NUM  3
1322 #define WINDOW_ENDING_NUM    4
1323 
1324 /*
1325 ** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
1326 ** value of the second argument to nth_value() (eCond==2) has just been
1327 ** evaluated and the result left in register reg. This function generates VM
1328 ** code to check that the value is a non-negative integer and throws an
1329 ** exception if it is not.
1330 */
1331 static void windowCheckValue(Parse *pParse, int reg, int eCond){
1332   static const char *azErr[] = {
1333     "frame starting offset must be a non-negative integer",
1334     "frame ending offset must be a non-negative integer",
1335     "second argument to nth_value must be a positive integer",
1336     "frame starting offset must be a non-negative number",
1337     "frame ending offset must be a non-negative number",
1338   };
1339   static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };
1340   Vdbe *v = sqlite3GetVdbe(pParse);
1341   int regZero = sqlite3GetTempReg(pParse);
1342   assert( eCond>=0 && eCond<ArraySize(azErr) );
1343   sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
1344   if( eCond>=WINDOW_STARTING_NUM ){
1345     int regString = sqlite3GetTempReg(pParse);
1346     sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
1347     sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);
1348     sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL);
1349     VdbeCoverage(v);
1350     assert( eCond==3 || eCond==4 );
1351     VdbeCoverageIf(v, eCond==3);
1352     VdbeCoverageIf(v, eCond==4);
1353   }else{
1354     sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
1355     VdbeCoverage(v);
1356     assert( eCond==0 || eCond==1 || eCond==2 );
1357     VdbeCoverageIf(v, eCond==0);
1358     VdbeCoverageIf(v, eCond==1);
1359     VdbeCoverageIf(v, eCond==2);
1360   }
1361   sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
1362   VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */
1363   VdbeCoverageNeverNullIf(v, eCond==1); /*   the OP_MustBeInt */
1364   VdbeCoverageNeverNullIf(v, eCond==2);
1365   VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */
1366   VdbeCoverageNeverNullIf(v, eCond==4); /*   the OP_Ge */
1367   sqlite3MayAbort(pParse);
1368   sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
1369   sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
1370   sqlite3ReleaseTempReg(pParse, regZero);
1371 }
1372 
1373 /*
1374 ** Return the number of arguments passed to the window-function associated
1375 ** with the object passed as the only argument to this function.
1376 */
1377 static int windowArgCount(Window *pWin){
1378   ExprList *pList = pWin->pOwner->x.pList;
1379   return (pList ? pList->nExpr : 0);
1380 }
1381 
1382 /*
1383 ** Generate VM code to invoke either xStep() (if bInverse is 0) or
1384 ** xInverse (if bInverse is non-zero) for each window function in the
1385 ** linked list starting at pMWin. Or, for built-in window functions
1386 ** that do not use the standard function API, generate the required
1387 ** inline VM code.
1388 **
1389 ** If argument csr is greater than or equal to 0, then argument reg is
1390 ** the first register in an array of registers guaranteed to be large
1391 ** enough to hold the array of arguments for each function. In this case
1392 ** the arguments are extracted from the current row of csr into the
1393 ** array of registers before invoking OP_AggStep or OP_AggInverse
1394 **
1395 ** Or, if csr is less than zero, then the array of registers at reg is
1396 ** already populated with all columns from the current row of the sub-query.
1397 **
1398 ** If argument regPartSize is non-zero, then it is a register containing the
1399 ** number of rows in the current partition.
1400 */
1401 static void windowAggStep(
1402   Parse *pParse,
1403   Window *pMWin,                  /* Linked list of window functions */
1404   int csr,                        /* Read arguments from this cursor */
1405   int bInverse,                   /* True to invoke xInverse instead of xStep */
1406   int reg                         /* Array of registers */
1407 ){
1408   Vdbe *v = sqlite3GetVdbe(pParse);
1409   Window *pWin;
1410   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1411     FuncDef *pFunc = pWin->pFunc;
1412     int regArg;
1413     int nArg = windowArgCount(pWin);
1414     int i;
1415 
1416     for(i=0; i<nArg; i++){
1417       if( i!=1 || pFunc->zName!=nth_valueName ){
1418         sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
1419       }else{
1420         sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
1421       }
1422     }
1423     regArg = reg;
1424 
1425     if( pMWin->regStartRowid==0
1426      && (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1427      && (pWin->eStart!=TK_UNBOUNDED)
1428     ){
1429       int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
1430       VdbeCoverage(v);
1431       if( bInverse==0 ){
1432         sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
1433         sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
1434         sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
1435         sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
1436       }else{
1437         sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
1438         VdbeCoverageNeverTaken(v);
1439         sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
1440         sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1441       }
1442       sqlite3VdbeJumpHere(v, addrIsNull);
1443     }else if( pWin->regApp ){
1444       assert( pFunc->zName==nth_valueName
1445            || pFunc->zName==first_valueName
1446       );
1447       assert( bInverse==0 || bInverse==1 );
1448       sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
1449     }else if( pFunc->xSFunc!=noopStepFunc ){
1450       int addrIf = 0;
1451       if( pWin->pFilter ){
1452         int regTmp;
1453         assert( nArg==0 || nArg==pWin->pOwner->x.pList->nExpr );
1454         assert( nArg || pWin->pOwner->x.pList==0 );
1455         regTmp = sqlite3GetTempReg(pParse);
1456         sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
1457         addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
1458         VdbeCoverage(v);
1459         sqlite3ReleaseTempReg(pParse, regTmp);
1460       }
1461       if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
1462         CollSeq *pColl;
1463         assert( nArg>0 );
1464         pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
1465         sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
1466       }
1467       sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
1468                         bInverse, regArg, pWin->regAccum);
1469       sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
1470       sqlite3VdbeChangeP5(v, (u8)nArg);
1471       if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
1472     }
1473   }
1474 }
1475 
1476 typedef struct WindowCodeArg WindowCodeArg;
1477 typedef struct WindowCsrAndReg WindowCsrAndReg;
1478 struct WindowCsrAndReg {
1479   int csr;
1480   int reg;
1481 };
1482 
1483 struct WindowCodeArg {
1484   Parse *pParse;
1485   Window *pMWin;
1486   Vdbe *pVdbe;
1487   int regGosub;
1488   int addrGosub;
1489   int regArg;
1490   int eDelete;
1491 
1492   WindowCsrAndReg start;
1493   WindowCsrAndReg current;
1494   WindowCsrAndReg end;
1495 };
1496 
1497 /*
1498 ** Values that may be passed as the second argument to windowCodeOp().
1499 */
1500 #define WINDOW_RETURN_ROW 1
1501 #define WINDOW_AGGINVERSE 2
1502 #define WINDOW_AGGSTEP    3
1503 
1504 /*
1505 ** Generate VM code to read the window frames peer values from cursor csr into
1506 ** an array of registers starting at reg.
1507 */
1508 static void windowReadPeerValues(
1509   WindowCodeArg *p,
1510   int csr,
1511   int reg
1512 ){
1513   Window *pMWin = p->pMWin;
1514   ExprList *pOrderBy = pMWin->pOrderBy;
1515   if( pOrderBy ){
1516     Vdbe *v = sqlite3GetVdbe(p->pParse);
1517     ExprList *pPart = pMWin->pPartition;
1518     int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
1519     int i;
1520     for(i=0; i<pOrderBy->nExpr; i++){
1521       sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
1522     }
1523   }
1524 }
1525 
1526 /*
1527 ** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
1528 ** (bFin==1) for each window function in the linked list starting at
1529 ** pMWin. Or, for built-in window-functions that do not use the standard
1530 ** API, generate the equivalent VM code.
1531 */
1532 static void windowAggFinal(WindowCodeArg *p, int bFin){
1533   Parse *pParse = p->pParse;
1534   Window *pMWin = p->pMWin;
1535   Vdbe *v = sqlite3GetVdbe(pParse);
1536   Window *pWin;
1537 
1538   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1539     if( pMWin->regStartRowid==0
1540      && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1541      && (pWin->eStart!=TK_UNBOUNDED)
1542     ){
1543       sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1544       sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
1545       VdbeCoverage(v);
1546       sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
1547       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1548     }else if( pWin->regApp ){
1549       assert( pMWin->regStartRowid==0 );
1550     }else{
1551       int nArg = windowArgCount(pWin);
1552       if( bFin ){
1553         sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
1554         sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
1555         sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
1556         sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1557       }else{
1558         sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
1559         sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
1560       }
1561     }
1562   }
1563 }
1564 
1565 /*
1566 ** Generate code to calculate the current values of all window functions in the
1567 ** p->pMWin list by doing a full scan of the current window frame. Store the
1568 ** results in the Window.regResult registers, ready to return the upper
1569 ** layer.
1570 */
1571 static void windowFullScan(WindowCodeArg *p){
1572   Window *pWin;
1573   Parse *pParse = p->pParse;
1574   Window *pMWin = p->pMWin;
1575   Vdbe *v = p->pVdbe;
1576 
1577   int regCRowid = 0;              /* Current rowid value */
1578   int regCPeer = 0;               /* Current peer values */
1579   int regRowid = 0;               /* AggStep rowid value */
1580   int regPeer = 0;                /* AggStep peer values */
1581 
1582   int nPeer;
1583   int lblNext;
1584   int lblBrk;
1585   int addrNext;
1586   int csr;
1587 
1588   assert( pMWin!=0 );
1589   csr = pMWin->csrApp;
1590   nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
1591 
1592   lblNext = sqlite3VdbeMakeLabel(pParse);
1593   lblBrk = sqlite3VdbeMakeLabel(pParse);
1594 
1595   regCRowid = sqlite3GetTempReg(pParse);
1596   regRowid = sqlite3GetTempReg(pParse);
1597   if( nPeer ){
1598     regCPeer = sqlite3GetTempRange(pParse, nPeer);
1599     regPeer = sqlite3GetTempRange(pParse, nPeer);
1600   }
1601 
1602   sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
1603   windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
1604 
1605   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1606     sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1607   }
1608 
1609   sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
1610   VdbeCoverage(v);
1611   addrNext = sqlite3VdbeCurrentAddr(v);
1612   sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);
1613   sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
1614   VdbeCoverageNeverNull(v);
1615 
1616   if( pMWin->eExclude==TK_CURRENT ){
1617     sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);
1618     VdbeCoverageNeverNull(v);
1619   }else if( pMWin->eExclude!=TK_NO ){
1620     int addr;
1621     int addrEq = 0;
1622     KeyInfo *pKeyInfo = 0;
1623 
1624     if( pMWin->pOrderBy ){
1625       pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
1626     }
1627     if( pMWin->eExclude==TK_TIES ){
1628       addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);
1629       VdbeCoverageNeverNull(v);
1630     }
1631     if( pKeyInfo ){
1632       windowReadPeerValues(p, csr, regPeer);
1633       sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);
1634       sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1635       addr = sqlite3VdbeCurrentAddr(v)+1;
1636       sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);
1637       VdbeCoverageEqNe(v);
1638     }else{
1639       sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);
1640     }
1641     if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);
1642   }
1643 
1644   windowAggStep(pParse, pMWin, csr, 0, p->regArg);
1645 
1646   sqlite3VdbeResolveLabel(v, lblNext);
1647   sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);
1648   VdbeCoverage(v);
1649   sqlite3VdbeJumpHere(v, addrNext-1);
1650   sqlite3VdbeJumpHere(v, addrNext+1);
1651   sqlite3ReleaseTempReg(pParse, regRowid);
1652   sqlite3ReleaseTempReg(pParse, regCRowid);
1653   if( nPeer ){
1654     sqlite3ReleaseTempRange(pParse, regPeer, nPeer);
1655     sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);
1656   }
1657 
1658   windowAggFinal(p, 1);
1659 }
1660 
1661 /*
1662 ** Invoke the sub-routine at regGosub (generated by code in select.c) to
1663 ** return the current row of Window.iEphCsr. If all window functions are
1664 ** aggregate window functions that use the standard API, a single
1665 ** OP_Gosub instruction is all that this routine generates. Extra VM code
1666 ** for per-row processing is only generated for the following built-in window
1667 ** functions:
1668 **
1669 **   nth_value()
1670 **   first_value()
1671 **   lag()
1672 **   lead()
1673 */
1674 static void windowReturnOneRow(WindowCodeArg *p){
1675   Window *pMWin = p->pMWin;
1676   Vdbe *v = p->pVdbe;
1677 
1678   if( pMWin->regStartRowid ){
1679     windowFullScan(p);
1680   }else{
1681     Parse *pParse = p->pParse;
1682     Window *pWin;
1683 
1684     for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1685       FuncDef *pFunc = pWin->pFunc;
1686       if( pFunc->zName==nth_valueName
1687        || pFunc->zName==first_valueName
1688       ){
1689         int csr = pWin->csrApp;
1690         int lbl = sqlite3VdbeMakeLabel(pParse);
1691         int tmpReg = sqlite3GetTempReg(pParse);
1692         sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1693 
1694         if( pFunc->zName==nth_valueName ){
1695           sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
1696           windowCheckValue(pParse, tmpReg, 2);
1697         }else{
1698           sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
1699         }
1700         sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
1701         sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
1702         VdbeCoverageNeverNull(v);
1703         sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
1704         VdbeCoverageNeverTaken(v);
1705         sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1706         sqlite3VdbeResolveLabel(v, lbl);
1707         sqlite3ReleaseTempReg(pParse, tmpReg);
1708       }
1709       else if( pFunc->zName==leadName || pFunc->zName==lagName ){
1710         int nArg = pWin->pOwner->x.pList->nExpr;
1711         int csr = pWin->csrApp;
1712         int lbl = sqlite3VdbeMakeLabel(pParse);
1713         int tmpReg = sqlite3GetTempReg(pParse);
1714         int iEph = pMWin->iEphCsr;
1715 
1716         if( nArg<3 ){
1717           sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1718         }else{
1719           sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
1720         }
1721         sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
1722         if( nArg<2 ){
1723           int val = (pFunc->zName==leadName ? 1 : -1);
1724           sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
1725         }else{
1726           int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
1727           int tmpReg2 = sqlite3GetTempReg(pParse);
1728           sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
1729           sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
1730           sqlite3ReleaseTempReg(pParse, tmpReg2);
1731         }
1732 
1733         sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
1734         VdbeCoverage(v);
1735         sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1736         sqlite3VdbeResolveLabel(v, lbl);
1737         sqlite3ReleaseTempReg(pParse, tmpReg);
1738       }
1739     }
1740   }
1741   sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
1742 }
1743 
1744 /*
1745 ** Generate code to set the accumulator register for each window function
1746 ** in the linked list passed as the second argument to NULL. And perform
1747 ** any equivalent initialization required by any built-in window functions
1748 ** in the list.
1749 */
1750 static int windowInitAccum(Parse *pParse, Window *pMWin){
1751   Vdbe *v = sqlite3GetVdbe(pParse);
1752   int regArg;
1753   int nArg = 0;
1754   Window *pWin;
1755   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1756     FuncDef *pFunc = pWin->pFunc;
1757     sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1758     nArg = MAX(nArg, windowArgCount(pWin));
1759     if( pMWin->regStartRowid==0 ){
1760       if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
1761         sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
1762         sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1763       }
1764 
1765       if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
1766         assert( pWin->eStart!=TK_UNBOUNDED );
1767         sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
1768         sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1769       }
1770     }
1771   }
1772   regArg = pParse->nMem+1;
1773   pParse->nMem += nArg;
1774   return regArg;
1775 }
1776 
1777 /*
1778 ** Return true if the current frame should be cached in the ephemeral table,
1779 ** even if there are no xInverse() calls required.
1780 */
1781 static int windowCacheFrame(Window *pMWin){
1782   Window *pWin;
1783   if( pMWin->regStartRowid ) return 1;
1784   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1785     FuncDef *pFunc = pWin->pFunc;
1786     if( (pFunc->zName==nth_valueName)
1787      || (pFunc->zName==first_valueName)
1788      || (pFunc->zName==leadName)
1789      || (pFunc->zName==lagName)
1790     ){
1791       return 1;
1792     }
1793   }
1794   return 0;
1795 }
1796 
1797 /*
1798 ** regOld and regNew are each the first register in an array of size
1799 ** pOrderBy->nExpr. This function generates code to compare the two
1800 ** arrays of registers using the collation sequences and other comparison
1801 ** parameters specified by pOrderBy.
1802 **
1803 ** If the two arrays are not equal, the contents of regNew is copied to
1804 ** regOld and control falls through. Otherwise, if the contents of the arrays
1805 ** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
1806 */
1807 static void windowIfNewPeer(
1808   Parse *pParse,
1809   ExprList *pOrderBy,
1810   int regNew,                     /* First in array of new values */
1811   int regOld,                     /* First in array of old values */
1812   int addr                        /* Jump here */
1813 ){
1814   Vdbe *v = sqlite3GetVdbe(pParse);
1815   if( pOrderBy ){
1816     int nVal = pOrderBy->nExpr;
1817     KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
1818     sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
1819     sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1820     sqlite3VdbeAddOp3(v, OP_Jump,
1821       sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
1822     );
1823     VdbeCoverageEqNe(v);
1824     sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
1825   }else{
1826     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
1827   }
1828 }
1829 
1830 /*
1831 ** This function is called as part of generating VM programs for RANGE
1832 ** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
1833 ** the ORDER BY term in the window, it generates code equivalent to:
1834 **
1835 **   if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
1836 **
1837 ** A special type of arithmetic is used such that if csr.peerVal is not
1838 ** a numeric type (real or integer), then the result of the addition is
1839 ** a copy of csr1.peerVal.
1840 */
1841 static void windowCodeRangeTest(
1842   WindowCodeArg *p,
1843   int op,                          /* OP_Ge or OP_Gt */
1844   int csr1,
1845   int regVal,
1846   int csr2,
1847   int lbl
1848 ){
1849   Parse *pParse = p->pParse;
1850   Vdbe *v = sqlite3GetVdbe(pParse);
1851   int reg1 = sqlite3GetTempReg(pParse);
1852   int reg2 = sqlite3GetTempReg(pParse);
1853   int arith = OP_Add;
1854   int addrGe;
1855 
1856   int regString = ++pParse->nMem;
1857 
1858   assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
1859   assert( p->pMWin->pOrderBy && p->pMWin->pOrderBy->nExpr==1 );
1860   if( p->pMWin->pOrderBy->a[0].sortOrder ){
1861     switch( op ){
1862       case OP_Ge: op = OP_Le; break;
1863       case OP_Gt: op = OP_Lt; break;
1864       default: assert( op==OP_Le ); op = OP_Ge; break;
1865     }
1866     arith = OP_Subtract;
1867   }
1868 
1869   windowReadPeerValues(p, csr1, reg1);
1870   windowReadPeerValues(p, csr2, reg2);
1871 
1872   /* Check if the peer value for csr1 value is a text or blob by comparing
1873   ** it to the smallest possible string - ''. If it is, jump over the
1874   ** OP_Add or OP_Subtract operation and proceed directly to the comparison. */
1875   sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
1876   addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
1877   VdbeCoverage(v);
1878   sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
1879   sqlite3VdbeJumpHere(v, addrGe);
1880   sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
1881   sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
1882   assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
1883   testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);
1884   testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt);
1885   testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le);
1886   testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt);
1887 
1888   sqlite3ReleaseTempReg(pParse, reg1);
1889   sqlite3ReleaseTempReg(pParse, reg2);
1890 }
1891 
1892 /*
1893 ** Helper function for sqlite3WindowCodeStep(). Each call to this function
1894 ** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
1895 ** operation. Refer to the header comment for sqlite3WindowCodeStep() for
1896 ** details.
1897 */
1898 static int windowCodeOp(
1899  WindowCodeArg *p,                /* Context object */
1900  int op,                          /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
1901  int regCountdown,                /* Register for OP_IfPos countdown */
1902  int jumpOnEof                    /* Jump here if stepped cursor reaches EOF */
1903 ){
1904   int csr, reg;
1905   Parse *pParse = p->pParse;
1906   Window *pMWin = p->pMWin;
1907   int ret = 0;
1908   Vdbe *v = p->pVdbe;
1909   int addrIf = 0;
1910   int addrContinue = 0;
1911   int addrGoto = 0;
1912   int bPeer = (pMWin->eFrmType!=TK_ROWS);
1913 
1914   int lblDone = sqlite3VdbeMakeLabel(pParse);
1915   int addrNextRange = 0;
1916 
1917   /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
1918   ** starts with UNBOUNDED PRECEDING. */
1919   if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
1920     assert( regCountdown==0 && jumpOnEof==0 );
1921     return 0;
1922   }
1923 
1924   if( regCountdown>0 ){
1925     if( pMWin->eFrmType==TK_RANGE ){
1926       addrNextRange = sqlite3VdbeCurrentAddr(v);
1927       assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );
1928       if( op==WINDOW_AGGINVERSE ){
1929         if( pMWin->eStart==TK_FOLLOWING ){
1930           windowCodeRangeTest(
1931               p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
1932           );
1933         }else{
1934           windowCodeRangeTest(
1935               p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
1936           );
1937         }
1938       }else{
1939         windowCodeRangeTest(
1940             p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
1941         );
1942       }
1943     }else{
1944       addrIf = sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, 0, 1);
1945       VdbeCoverage(v);
1946     }
1947   }
1948 
1949   if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
1950     windowAggFinal(p, 0);
1951   }
1952   addrContinue = sqlite3VdbeCurrentAddr(v);
1953   switch( op ){
1954     case WINDOW_RETURN_ROW:
1955       csr = p->current.csr;
1956       reg = p->current.reg;
1957       windowReturnOneRow(p);
1958       break;
1959 
1960     case WINDOW_AGGINVERSE:
1961       csr = p->start.csr;
1962       reg = p->start.reg;
1963       if( pMWin->regStartRowid ){
1964         assert( pMWin->regEndRowid );
1965         sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
1966       }else{
1967         windowAggStep(pParse, pMWin, csr, 1, p->regArg);
1968       }
1969       break;
1970 
1971     default:
1972       assert( op==WINDOW_AGGSTEP );
1973       csr = p->end.csr;
1974       reg = p->end.reg;
1975       if( pMWin->regStartRowid ){
1976         assert( pMWin->regEndRowid );
1977         sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
1978       }else{
1979         windowAggStep(pParse, pMWin, csr, 0, p->regArg);
1980       }
1981       break;
1982   }
1983 
1984   if( op==p->eDelete ){
1985     sqlite3VdbeAddOp1(v, OP_Delete, csr);
1986     sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
1987   }
1988 
1989   if( jumpOnEof ){
1990     sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
1991     VdbeCoverage(v);
1992     ret = sqlite3VdbeAddOp0(v, OP_Goto);
1993   }else{
1994     sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
1995     VdbeCoverage(v);
1996     if( bPeer ){
1997       addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
1998     }
1999   }
2000 
2001   if( bPeer ){
2002     int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
2003     int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
2004     windowReadPeerValues(p, csr, regTmp);
2005     windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
2006     sqlite3ReleaseTempRange(pParse, regTmp, nReg);
2007   }
2008 
2009   if( addrNextRange ){
2010     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
2011   }
2012   sqlite3VdbeResolveLabel(v, lblDone);
2013   if( addrGoto ) sqlite3VdbeJumpHere(v, addrGoto);
2014   if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
2015   return ret;
2016 }
2017 
2018 
2019 /*
2020 ** Allocate and return a duplicate of the Window object indicated by the
2021 ** third argument. Set the Window.pOwner field of the new object to
2022 ** pOwner.
2023 */
2024 Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
2025   Window *pNew = 0;
2026   if( ALWAYS(p) ){
2027     pNew = sqlite3DbMallocZero(db, sizeof(Window));
2028     if( pNew ){
2029       pNew->zName = sqlite3DbStrDup(db, p->zName);
2030       pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
2031       pNew->pFunc = p->pFunc;
2032       pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
2033       pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
2034       pNew->eFrmType = p->eFrmType;
2035       pNew->eEnd = p->eEnd;
2036       pNew->eStart = p->eStart;
2037       pNew->eExclude = p->eExclude;
2038       pNew->regResult = p->regResult;
2039       pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
2040       pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
2041       pNew->pOwner = pOwner;
2042     }
2043   }
2044   return pNew;
2045 }
2046 
2047 /*
2048 ** Return a copy of the linked list of Window objects passed as the
2049 ** second argument.
2050 */
2051 Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
2052   Window *pWin;
2053   Window *pRet = 0;
2054   Window **pp = &pRet;
2055 
2056   for(pWin=p; pWin; pWin=pWin->pNextWin){
2057     *pp = sqlite3WindowDup(db, 0, pWin);
2058     if( *pp==0 ) break;
2059     pp = &((*pp)->pNextWin);
2060   }
2061 
2062   return pRet;
2063 }
2064 
2065 /*
2066 ** Return true if it can be determined at compile time that expression
2067 ** pExpr evaluates to a value that, when cast to an integer, is greater
2068 ** than zero. False otherwise.
2069 **
2070 ** If an OOM error occurs, this function sets the Parse.db.mallocFailed
2071 ** flag and returns zero.
2072 */
2073 static int windowExprGtZero(Parse *pParse, Expr *pExpr){
2074   int ret = 0;
2075   sqlite3 *db = pParse->db;
2076   sqlite3_value *pVal = 0;
2077   sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);
2078   if( pVal && sqlite3_value_int(pVal)>0 ){
2079     ret = 1;
2080   }
2081   sqlite3ValueFree(pVal);
2082   return ret;
2083 }
2084 
2085 /*
2086 ** sqlite3WhereBegin() has already been called for the SELECT statement
2087 ** passed as the second argument when this function is invoked. It generates
2088 ** code to populate the Window.regResult register for each window function
2089 ** and invoke the sub-routine at instruction addrGosub once for each row.
2090 ** sqlite3WhereEnd() is always called before returning.
2091 **
2092 ** This function handles several different types of window frames, which
2093 ** require slightly different processing. The following pseudo code is
2094 ** used to implement window frames of the form:
2095 **
2096 **   ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
2097 **
2098 ** Other window frame types use variants of the following:
2099 **
2100 **     ... loop started by sqlite3WhereBegin() ...
2101 **       if( new partition ){
2102 **         Gosub flush
2103 **       }
2104 **       Insert new row into eph table.
2105 **
2106 **       if( first row of partition ){
2107 **         // Rewind three cursors, all open on the eph table.
2108 **         Rewind(csrEnd);
2109 **         Rewind(csrStart);
2110 **         Rewind(csrCurrent);
2111 **
2112 **         regEnd = <expr2>          // FOLLOWING expression
2113 **         regStart = <expr1>        // PRECEDING expression
2114 **       }else{
2115 **         // First time this branch is taken, the eph table contains two
2116 **         // rows. The first row in the partition, which all three cursors
2117 **         // currently point to, and the following row.
2118 **         AGGSTEP
2119 **         if( (regEnd--)<=0 ){
2120 **           RETURN_ROW
2121 **           if( (regStart--)<=0 ){
2122 **             AGGINVERSE
2123 **           }
2124 **         }
2125 **       }
2126 **     }
2127 **     flush:
2128 **       AGGSTEP
2129 **       while( 1 ){
2130 **         RETURN ROW
2131 **         if( csrCurrent is EOF ) break;
2132 **         if( (regStart--)<=0 ){
2133 **           AggInverse(csrStart)
2134 **           Next(csrStart)
2135 **         }
2136 **       }
2137 **
2138 ** The pseudo-code above uses the following shorthand:
2139 **
2140 **   AGGSTEP:    invoke the aggregate xStep() function for each window function
2141 **               with arguments read from the current row of cursor csrEnd, then
2142 **               step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
2143 **
2144 **   RETURN_ROW: return a row to the caller based on the contents of the
2145 **               current row of csrCurrent and the current state of all
2146 **               aggregates. Then step cursor csrCurrent forward one row.
2147 **
2148 **   AGGINVERSE: invoke the aggregate xInverse() function for each window
2149 **               functions with arguments read from the current row of cursor
2150 **               csrStart. Then step csrStart forward one row.
2151 **
2152 ** There are two other ROWS window frames that are handled significantly
2153 ** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
2154 ** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
2155 ** cases because they change the order in which the three cursors (csrStart,
2156 ** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
2157 ** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
2158 ** three.
2159 **
2160 **   ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2161 **
2162 **     ... loop started by sqlite3WhereBegin() ...
2163 **       if( new partition ){
2164 **         Gosub flush
2165 **       }
2166 **       Insert new row into eph table.
2167 **       if( first row of partition ){
2168 **         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2169 **         regEnd = <expr2>
2170 **         regStart = <expr1>
2171 **       }else{
2172 **         if( (regEnd--)<=0 ){
2173 **           AGGSTEP
2174 **         }
2175 **         RETURN_ROW
2176 **         if( (regStart--)<=0 ){
2177 **           AGGINVERSE
2178 **         }
2179 **       }
2180 **     }
2181 **     flush:
2182 **       if( (regEnd--)<=0 ){
2183 **         AGGSTEP
2184 **       }
2185 **       RETURN_ROW
2186 **
2187 **
2188 **   ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2189 **
2190 **     ... loop started by sqlite3WhereBegin() ...
2191 **     if( new partition ){
2192 **       Gosub flush
2193 **     }
2194 **     Insert new row into eph table.
2195 **     if( first row of partition ){
2196 **       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2197 **       regEnd = <expr2>
2198 **       regStart = regEnd - <expr1>
2199 **     }else{
2200 **       AGGSTEP
2201 **       if( (regEnd--)<=0 ){
2202 **         RETURN_ROW
2203 **       }
2204 **       if( (regStart--)<=0 ){
2205 **         AGGINVERSE
2206 **       }
2207 **     }
2208 **   }
2209 **   flush:
2210 **     AGGSTEP
2211 **     while( 1 ){
2212 **       if( (regEnd--)<=0 ){
2213 **         RETURN_ROW
2214 **         if( eof ) break;
2215 **       }
2216 **       if( (regStart--)<=0 ){
2217 **         AGGINVERSE
2218 **         if( eof ) break
2219 **       }
2220 **     }
2221 **     while( !eof csrCurrent ){
2222 **       RETURN_ROW
2223 **     }
2224 **
2225 ** For the most part, the patterns above are adapted to support UNBOUNDED by
2226 ** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
2227 ** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING".
2228 ** This is optimized of course - branches that will never be taken and
2229 ** conditions that are always true are omitted from the VM code. The only
2230 ** exceptional case is:
2231 **
2232 **   ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
2233 **
2234 **     ... loop started by sqlite3WhereBegin() ...
2235 **     if( new partition ){
2236 **       Gosub flush
2237 **     }
2238 **     Insert new row into eph table.
2239 **     if( first row of partition ){
2240 **       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2241 **       regStart = <expr1>
2242 **     }else{
2243 **       AGGSTEP
2244 **     }
2245 **   }
2246 **   flush:
2247 **     AGGSTEP
2248 **     while( 1 ){
2249 **       if( (regStart--)<=0 ){
2250 **         AGGINVERSE
2251 **         if( eof ) break
2252 **       }
2253 **       RETURN_ROW
2254 **     }
2255 **     while( !eof csrCurrent ){
2256 **       RETURN_ROW
2257 **     }
2258 **
2259 ** Also requiring special handling are the cases:
2260 **
2261 **   ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2262 **   ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2263 **
2264 ** when (expr1 < expr2). This is detected at runtime, not by this function.
2265 ** To handle this case, the pseudo-code programs depicted above are modified
2266 ** slightly to be:
2267 **
2268 **     ... loop started by sqlite3WhereBegin() ...
2269 **     if( new partition ){
2270 **       Gosub flush
2271 **     }
2272 **     Insert new row into eph table.
2273 **     if( first row of partition ){
2274 **       Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2275 **       regEnd = <expr2>
2276 **       regStart = <expr1>
2277 **       if( regEnd < regStart ){
2278 **         RETURN_ROW
2279 **         delete eph table contents
2280 **         continue
2281 **       }
2282 **     ...
2283 **
2284 ** The new "continue" statement in the above jumps to the next iteration
2285 ** of the outer loop - the one started by sqlite3WhereBegin().
2286 **
2287 ** The various GROUPS cases are implemented using the same patterns as
2288 ** ROWS. The VM code is modified slightly so that:
2289 **
2290 **   1. The else branch in the main loop is only taken if the row just
2291 **      added to the ephemeral table is the start of a new group. In
2292 **      other words, it becomes:
2293 **
2294 **         ... loop started by sqlite3WhereBegin() ...
2295 **         if( new partition ){
2296 **           Gosub flush
2297 **         }
2298 **         Insert new row into eph table.
2299 **         if( first row of partition ){
2300 **           Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2301 **           regEnd = <expr2>
2302 **           regStart = <expr1>
2303 **         }else if( new group ){
2304 **           ...
2305 **         }
2306 **       }
2307 **
2308 **   2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
2309 **      AGGINVERSE step processes the current row of the relevant cursor and
2310 **      all subsequent rows belonging to the same group.
2311 **
2312 ** RANGE window frames are a little different again. As for GROUPS, the
2313 ** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
2314 ** deal in groups instead of rows. As for ROWS and GROUPS, there are three
2315 ** basic cases:
2316 **
2317 **   RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
2318 **
2319 **     ... loop started by sqlite3WhereBegin() ...
2320 **       if( new partition ){
2321 **         Gosub flush
2322 **       }
2323 **       Insert new row into eph table.
2324 **       if( first row of partition ){
2325 **         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2326 **         regEnd = <expr2>
2327 **         regStart = <expr1>
2328 **       }else{
2329 **         AGGSTEP
2330 **         while( (csrCurrent.key + regEnd) < csrEnd.key ){
2331 **           RETURN_ROW
2332 **           while( csrStart.key + regStart) < csrCurrent.key ){
2333 **             AGGINVERSE
2334 **           }
2335 **         }
2336 **       }
2337 **     }
2338 **     flush:
2339 **       AGGSTEP
2340 **       while( 1 ){
2341 **         RETURN ROW
2342 **         if( csrCurrent is EOF ) break;
2343 **           while( csrStart.key + regStart) < csrCurrent.key ){
2344 **             AGGINVERSE
2345 **           }
2346 **         }
2347 **       }
2348 **
2349 ** In the above notation, "csr.key" means the current value of the ORDER BY
2350 ** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
2351 ** or <expr PRECEDING) read from cursor csr.
2352 **
2353 **   RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2354 **
2355 **     ... loop started by sqlite3WhereBegin() ...
2356 **       if( new partition ){
2357 **         Gosub flush
2358 **       }
2359 **       Insert new row into eph table.
2360 **       if( first row of partition ){
2361 **         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2362 **         regEnd = <expr2>
2363 **         regStart = <expr1>
2364 **       }else{
2365 **         if( (csrEnd.key + regEnd) <= csrCurrent.key ){
2366 **           AGGSTEP
2367 **         }
2368 **         while( (csrStart.key + regStart) < csrCurrent.key ){
2369 **           AGGINVERSE
2370 **         }
2371 **         RETURN_ROW
2372 **       }
2373 **     }
2374 **     flush:
2375 **       while( (csrEnd.key + regEnd) <= csrCurrent.key ){
2376 **         AGGSTEP
2377 **       }
2378 **       while( (csrStart.key + regStart) < csrCurrent.key ){
2379 **         AGGINVERSE
2380 **       }
2381 **       RETURN_ROW
2382 **
2383 **   RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2384 **
2385 **     ... loop started by sqlite3WhereBegin() ...
2386 **       if( new partition ){
2387 **         Gosub flush
2388 **       }
2389 **       Insert new row into eph table.
2390 **       if( first row of partition ){
2391 **         Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2392 **         regEnd = <expr2>
2393 **         regStart = <expr1>
2394 **       }else{
2395 **         AGGSTEP
2396 **         while( (csrCurrent.key + regEnd) < csrEnd.key ){
2397 **           while( (csrCurrent.key + regStart) > csrStart.key ){
2398 **             AGGINVERSE
2399 **           }
2400 **           RETURN_ROW
2401 **         }
2402 **       }
2403 **     }
2404 **     flush:
2405 **       AGGSTEP
2406 **       while( 1 ){
2407 **         while( (csrCurrent.key + regStart) > csrStart.key ){
2408 **           AGGINVERSE
2409 **           if( eof ) break "while( 1 )" loop.
2410 **         }
2411 **         RETURN_ROW
2412 **       }
2413 **       while( !eof csrCurrent ){
2414 **         RETURN_ROW
2415 **       }
2416 **
2417 ** The text above leaves out many details. Refer to the code and comments
2418 ** below for a more complete picture.
2419 */
2420 void sqlite3WindowCodeStep(
2421   Parse *pParse,                  /* Parse context */
2422   Select *p,                      /* Rewritten SELECT statement */
2423   WhereInfo *pWInfo,              /* Context returned by sqlite3WhereBegin() */
2424   int regGosub,                   /* Register for OP_Gosub */
2425   int addrGosub                   /* OP_Gosub here to return each row */
2426 ){
2427   Window *pMWin = p->pWin;
2428   ExprList *pOrderBy = pMWin->pOrderBy;
2429   Vdbe *v = sqlite3GetVdbe(pParse);
2430   int csrWrite;                   /* Cursor used to write to eph. table */
2431   int csrInput = p->pSrc->a[0].iCursor;     /* Cursor of sub-select */
2432   int nInput = p->pSrc->a[0].pTab->nCol;    /* Number of cols returned by sub */
2433   int iInput;                               /* To iterate through sub cols */
2434   int addrNe;                     /* Address of OP_Ne */
2435   int addrGosubFlush = 0;         /* Address of OP_Gosub to flush: */
2436   int addrInteger = 0;            /* Address of OP_Integer */
2437   int addrEmpty;                  /* Address of OP_Rewind in flush: */
2438   int regStart = 0;               /* Value of <expr> PRECEDING */
2439   int regEnd = 0;                 /* Value of <expr> FOLLOWING */
2440   int regNew;                     /* Array of registers holding new input row */
2441   int regRecord;                  /* regNew array in record form */
2442   int regRowid;                   /* Rowid for regRecord in eph table */
2443   int regNewPeer = 0;             /* Peer values for new row (part of regNew) */
2444   int regPeer = 0;                /* Peer values for current row */
2445   int regFlushPart = 0;           /* Register for "Gosub flush_partition" */
2446   WindowCodeArg s;                /* Context object for sub-routines */
2447   int lblWhereEnd;                /* Label just before sqlite3WhereEnd() code */
2448 
2449   assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
2450        || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
2451   );
2452   assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
2453        || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
2454   );
2455   assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
2456        || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
2457        || pMWin->eExclude==TK_NO
2458   );
2459 
2460   lblWhereEnd = sqlite3VdbeMakeLabel(pParse);
2461 
2462   /* Fill in the context object */
2463   memset(&s, 0, sizeof(WindowCodeArg));
2464   s.pParse = pParse;
2465   s.pMWin = pMWin;
2466   s.pVdbe = v;
2467   s.regGosub = regGosub;
2468   s.addrGosub = addrGosub;
2469   s.current.csr = pMWin->iEphCsr;
2470   csrWrite = s.current.csr+1;
2471   s.start.csr = s.current.csr+2;
2472   s.end.csr = s.current.csr+3;
2473 
2474   /* Figure out when rows may be deleted from the ephemeral table. There
2475   ** are four options - they may never be deleted (eDelete==0), they may
2476   ** be deleted as soon as they are no longer part of the window frame
2477   ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
2478   ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
2479   ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
2480   switch( pMWin->eStart ){
2481     case TK_FOLLOWING:
2482       if( pMWin->eFrmType!=TK_RANGE
2483        && windowExprGtZero(pParse, pMWin->pStart)
2484       ){
2485         s.eDelete = WINDOW_RETURN_ROW;
2486       }
2487       break;
2488     case TK_UNBOUNDED:
2489       if( windowCacheFrame(pMWin)==0 ){
2490         if( pMWin->eEnd==TK_PRECEDING ){
2491           if( pMWin->eFrmType!=TK_RANGE
2492            && windowExprGtZero(pParse, pMWin->pEnd)
2493           ){
2494             s.eDelete = WINDOW_AGGSTEP;
2495           }
2496         }else{
2497           s.eDelete = WINDOW_RETURN_ROW;
2498         }
2499       }
2500       break;
2501     default:
2502       s.eDelete = WINDOW_AGGINVERSE;
2503       break;
2504   }
2505 
2506   /* Allocate registers for the array of values from the sub-query, the
2507   ** samve values in record form, and the rowid used to insert said record
2508   ** into the ephemeral table.  */
2509   regNew = pParse->nMem+1;
2510   pParse->nMem += nInput;
2511   regRecord = ++pParse->nMem;
2512   regRowid = ++pParse->nMem;
2513 
2514   /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
2515   ** clause, allocate registers to store the results of evaluating each
2516   ** <expr>.  */
2517   if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
2518     regStart = ++pParse->nMem;
2519   }
2520   if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
2521     regEnd = ++pParse->nMem;
2522   }
2523 
2524   /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
2525   ** registers to store copies of the ORDER BY expressions (peer values)
2526   ** for the main loop, and for each cursor (start, current and end). */
2527   if( pMWin->eFrmType!=TK_ROWS ){
2528     int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
2529     regNewPeer = regNew + pMWin->nBufferCol;
2530     if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
2531     regPeer = pParse->nMem+1;       pParse->nMem += nPeer;
2532     s.start.reg = pParse->nMem+1;   pParse->nMem += nPeer;
2533     s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
2534     s.end.reg = pParse->nMem+1;     pParse->nMem += nPeer;
2535   }
2536 
2537   /* Load the column values for the row returned by the sub-select
2538   ** into an array of registers starting at regNew. Assemble them into
2539   ** a record in register regRecord. */
2540   for(iInput=0; iInput<nInput; iInput++){
2541     sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
2542   }
2543   sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
2544 
2545   /* An input row has just been read into an array of registers starting
2546   ** at regNew. If the window has a PARTITION clause, this block generates
2547   ** VM code to check if the input row is the start of a new partition.
2548   ** If so, it does an OP_Gosub to an address to be filled in later. The
2549   ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
2550   if( pMWin->pPartition ){
2551     int addr;
2552     ExprList *pPart = pMWin->pPartition;
2553     int nPart = pPart->nExpr;
2554     int regNewPart = regNew + pMWin->nBufferCol;
2555     KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
2556 
2557     regFlushPart = ++pParse->nMem;
2558     addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
2559     sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
2560     sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
2561     VdbeCoverageEqNe(v);
2562     addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
2563     VdbeComment((v, "call flush_partition"));
2564     sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
2565   }
2566 
2567   /* Insert the new row into the ephemeral table */
2568   sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid);
2569   sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid);
2570   addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid);
2571   VdbeCoverageNeverNull(v);
2572 
2573   /* This block is run for the first row of each partition */
2574   s.regArg = windowInitAccum(pParse, pMWin);
2575 
2576   if( regStart ){
2577     sqlite3ExprCode(pParse, pMWin->pStart, regStart);
2578     windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE ? 3 : 0));
2579   }
2580   if( regEnd ){
2581     sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
2582     windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE ? 3 : 0));
2583   }
2584 
2585   if( pMWin->eStart==pMWin->eEnd && regStart ){
2586     int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
2587     int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
2588     VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */
2589     VdbeCoverageNeverNullIf(v, op==OP_Le); /*   values previously checked */
2590     windowAggFinal(&s, 0);
2591     sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
2592     VdbeCoverageNeverTaken(v);
2593     windowReturnOneRow(&s);
2594     sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
2595     sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
2596     sqlite3VdbeJumpHere(v, addrGe);
2597   }
2598   if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){
2599     assert( pMWin->eEnd==TK_FOLLOWING );
2600     sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
2601   }
2602 
2603   if( pMWin->eStart!=TK_UNBOUNDED ){
2604     sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1);
2605     VdbeCoverageNeverTaken(v);
2606   }
2607   sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
2608   VdbeCoverageNeverTaken(v);
2609   sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1);
2610   VdbeCoverageNeverTaken(v);
2611   if( regPeer && pOrderBy ){
2612     sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
2613     sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
2614     sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
2615     sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
2616   }
2617 
2618   sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
2619 
2620   sqlite3VdbeJumpHere(v, addrNe);
2621 
2622   /* Beginning of the block executed for the second and subsequent rows. */
2623   if( regPeer ){
2624     windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);
2625   }
2626   if( pMWin->eStart==TK_FOLLOWING ){
2627     windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
2628     if( pMWin->eEnd!=TK_UNBOUNDED ){
2629       if( pMWin->eFrmType==TK_RANGE ){
2630         int lbl = sqlite3VdbeMakeLabel(pParse);
2631         int addrNext = sqlite3VdbeCurrentAddr(v);
2632         windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2633         windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2634         windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2635         sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
2636         sqlite3VdbeResolveLabel(v, lbl);
2637       }else{
2638         windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
2639         windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2640       }
2641     }
2642   }else
2643   if( pMWin->eEnd==TK_PRECEDING ){
2644     int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
2645     windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
2646     if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2647     windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2648     if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2649   }else{
2650     int addr = 0;
2651     windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
2652     if( pMWin->eEnd!=TK_UNBOUNDED ){
2653       if( pMWin->eFrmType==TK_RANGE ){
2654         int lbl = 0;
2655         addr = sqlite3VdbeCurrentAddr(v);
2656         if( regEnd ){
2657           lbl = sqlite3VdbeMakeLabel(pParse);
2658           windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2659         }
2660         windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2661         windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2662         if( regEnd ){
2663           sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
2664           sqlite3VdbeResolveLabel(v, lbl);
2665         }
2666       }else{
2667         if( regEnd ){
2668           addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
2669           VdbeCoverage(v);
2670         }
2671         windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2672         windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2673         if( regEnd ) sqlite3VdbeJumpHere(v, addr);
2674       }
2675     }
2676   }
2677 
2678   /* End of the main input loop */
2679   sqlite3VdbeResolveLabel(v, lblWhereEnd);
2680   sqlite3WhereEnd(pWInfo);
2681 
2682   /* Fall through */
2683   if( pMWin->pPartition ){
2684     addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
2685     sqlite3VdbeJumpHere(v, addrGosubFlush);
2686   }
2687 
2688   addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
2689   VdbeCoverage(v);
2690   if( pMWin->eEnd==TK_PRECEDING ){
2691     int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
2692     windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
2693     if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2694     windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2695   }else if( pMWin->eStart==TK_FOLLOWING ){
2696     int addrStart;
2697     int addrBreak1;
2698     int addrBreak2;
2699     int addrBreak3;
2700     windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
2701     if( pMWin->eFrmType==TK_RANGE ){
2702       addrStart = sqlite3VdbeCurrentAddr(v);
2703       addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
2704       addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
2705     }else
2706     if( pMWin->eEnd==TK_UNBOUNDED ){
2707       addrStart = sqlite3VdbeCurrentAddr(v);
2708       addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
2709       addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
2710     }else{
2711       assert( pMWin->eEnd==TK_FOLLOWING );
2712       addrStart = sqlite3VdbeCurrentAddr(v);
2713       addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
2714       addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
2715     }
2716     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2717     sqlite3VdbeJumpHere(v, addrBreak2);
2718     addrStart = sqlite3VdbeCurrentAddr(v);
2719     addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
2720     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2721     sqlite3VdbeJumpHere(v, addrBreak1);
2722     sqlite3VdbeJumpHere(v, addrBreak3);
2723   }else{
2724     int addrBreak;
2725     int addrStart;
2726     windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
2727     addrStart = sqlite3VdbeCurrentAddr(v);
2728     addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
2729     windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2730     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2731     sqlite3VdbeJumpHere(v, addrBreak);
2732   }
2733   sqlite3VdbeJumpHere(v, addrEmpty);
2734 
2735   sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
2736   if( pMWin->pPartition ){
2737     if( pMWin->regStartRowid ){
2738       sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
2739       sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
2740     }
2741     sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
2742     sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
2743   }
2744 }
2745 
2746 #endif /* SQLITE_OMIT_WINDOWFUNC */
2747