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