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