Merge branch 'master' into prerelease
[sqlcipher.git] / src / window.c
blob2afa7c12ce0606dc6bcdf61d8e61059287ed1b19
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.
11 *************************************************************************
13 #include "sqliteInt.h"
15 #ifndef SQLITE_OMIT_WINDOWFUNC
18 ** SELECT REWRITING
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:
26 ** CREATE TABLE t1(a, b, c, d, e, f, g);
28 ** the statement:
30 ** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e;
32 ** is transformed to:
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;
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:
43 ** * FROM, WHERE, GROUP BY and HAVING clauses are all moved to
44 ** the sub-query.
46 ** * ORDER BY, LIMIT and OFFSET remain part of the parent query.
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.
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:
57 ** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
58 ** min(e) OVER (PARTITION BY c ORDER BY d)
59 ** FROM t1;
61 ** is transformed in the same way as the example above. However:
63 ** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
64 ** min(e) OVER (PARTITION BY a ORDER BY b)
65 ** FROM t1;
67 ** Must be transformed to:
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;
75 ** so that both min() and max() may process rows in the order defined by
76 ** their respective window declarations.
78 ** INTERFACE WITH SELECT.C
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().
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:
90 ** * The results of all window-functions for the row are stored
91 ** in the associated Window.regResult registers.
93 ** * The required terminal values are stored in the current row of
94 ** temp table Window.iEphCsr.
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.
102 ** BUILT-IN WINDOW FUNCTIONS
104 ** This implementation features the following built-in window functions:
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)
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:
131 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
133 ** See sqlite3WindowUpdate() for details.
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.
142 ** Implementation of built-in window function row_number(). Assumes that the
143 ** window frame has been coerced to:
145 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
147 static void row_numberStepFunc(
148 sqlite3_context *pCtx,
149 int nArg,
150 sqlite3_value **apArg
152 i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
153 if( p ) (*p)++;
154 UNUSED_PARAMETER(nArg);
155 UNUSED_PARAMETER(apArg);
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));
163 ** Context object type used by rank(), dense_rank(), percent_rank() and
164 ** cume_dist().
166 struct CallCount {
167 i64 nValue;
168 i64 nStep;
169 i64 nTotal;
173 ** Implementation of built-in window function dense_rank(). Assumes that
174 ** the window frame has been set to:
176 ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
178 static void dense_rankStepFunc(
179 sqlite3_context *pCtx,
180 int nArg,
181 sqlite3_value **apArg
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);
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;
197 sqlite3_result_int64(pCtx, p->nValue);
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".
206 struct NthValueCtx {
207 i64 nStep;
208 sqlite3_value *pValue;
210 static void nth_valueStepFunc(
211 sqlite3_context *pCtx,
212 int nArg,
213 sqlite3_value **apArg
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;
229 default:
230 goto error_out;
232 if( iVal<=0 ) goto error_out;
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);
242 UNUSED_PARAMETER(nArg);
243 UNUSED_PARAMETER(apArg);
244 return;
246 error_out:
247 sqlite3_result_error(
248 pCtx, "second argument to nth_value must be a positive integer", -1
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;
260 #define nth_valueInvFunc noopStepFunc
261 #define nth_valueValueFunc noopValueFunc
263 static void first_valueStepFunc(
264 sqlite3_context *pCtx,
265 int nArg,
266 sqlite3_value **apArg
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);
276 UNUSED_PARAMETER(nArg);
277 UNUSED_PARAMETER(apArg);
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;
288 #define first_valueInvFunc noopStepFunc
289 #define first_valueValueFunc noopValueFunc
292 ** Implementation of built-in window function rank(). Assumes that
293 ** the window frame has been set to:
295 ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
297 static void rankStepFunc(
298 sqlite3_context *pCtx,
299 int nArg,
300 sqlite3_value **apArg
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;
310 UNUSED_PARAMETER(nArg);
311 UNUSED_PARAMETER(apArg);
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;
323 ** Implementation of built-in window function percent_rank(). Assumes that
324 ** the window frame has been set to:
326 ** GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
328 static void percent_rankStepFunc(
329 sqlite3_context *pCtx,
330 int nArg,
331 sqlite3_value **apArg
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++;
341 static void percent_rankInvFunc(
342 sqlite3_context *pCtx,
343 int nArg,
344 sqlite3_value **apArg
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++;
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);
365 #define percent_rankFinalizeFunc percent_rankValueFunc
368 ** Implementation of built-in window function cume_dist(). Assumes that
369 ** the window frame has been set to:
371 ** GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
373 static void cume_distStepFunc(
374 sqlite3_context *pCtx,
375 int nArg,
376 sqlite3_value **apArg
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++;
386 static void cume_distInvFunc(
387 sqlite3_context *pCtx,
388 int nArg,
389 sqlite3_value **apArg
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++;
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);
405 #define cume_distFinalizeFunc cume_distValueFunc
408 ** Context object for ntile() window function.
410 struct NtileCtx {
411 i64 nTotal; /* Total rows in partition */
412 i64 nParam; /* Parameter passed to ntile(N) */
413 i64 iRow; /* Current row */
417 ** Implementation of ntile(). This assumes that the window frame has
418 ** been coerced to:
420 ** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING
422 static void ntileStepFunc(
423 sqlite3_context *pCtx,
424 int nArg,
425 sqlite3_value **apArg
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
439 p->nTotal++;
442 static void ntileInvFunc(
443 sqlite3_context *pCtx,
444 int nArg,
445 sqlite3_value **apArg
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++;
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;
465 assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
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);
475 #define ntileFinalizeFunc ntileValueFunc
478 ** Context object for last_value() window function.
480 struct LastValueCtx {
481 sqlite3_value *pVal;
482 int nVal;
486 ** Implementation of last_value().
488 static void last_valueStepFunc(
489 sqlite3_context *pCtx,
490 int nArg,
491 sqlite3_value **apArg
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++;
506 static void last_valueInvFunc(
507 sqlite3_context *pCtx,
508 int nArg,
509 sqlite3_value **apArg
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;
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);
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;
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:
546 ** if( pFuncDef->zName==row_valueName ){ ... }
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";
561 ** No-op implementations of xStep() and xFinalize(). Used as place-holders
562 ** for built-in window functions that never call those interfaces.
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.
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*/ }
581 /* Window functions that use all window interfaces: xStep, xFinal,
582 ** xValue, and xInverse */
583 #define WINDOWFUNCALL(name,nArg,extra) { \
584 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
585 name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \
586 name ## InvFunc, name ## Name, {0} \
589 /* Window functions that are implemented using bytecode and thus have
590 ** no-op routines for their methods */
591 #define WINDOWFUNCNOOP(name,nArg,extra) { \
592 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
593 noopStepFunc, noopValueFunc, noopValueFunc, \
594 noopStepFunc, name ## Name, {0} \
597 /* Window functions that use all window interfaces: xStep, the
598 ** same routine for xFinalize and xValue and which never call
599 ** xInverse. */
600 #define WINDOWFUNCX(name,nArg,extra) { \
601 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
602 name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
603 noopStepFunc, name ## Name, {0} \
608 ** Register those built-in window functions that are not also aggregates.
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),
628 sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
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;
636 if( p==0 ){
637 sqlite3ErrorMsg(pParse, "no such window: %s", zName);
639 return p;
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:
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.
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.
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 */
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);
679 if( (pWin->eFrmType==TK_RANGE)
680 && (pWin->pStart || pWin->pEnd)
681 && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)
683 sqlite3ErrorMsg(pParse,
684 "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression"
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"
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 },
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");
722 break;
727 pWin->pFunc = pFunc;
731 ** Context object passed through sqlite3WalkExprList() to
732 ** selectWindowRewriteExprCb() by selectWindowRewriteEList().
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 */
744 ** Callback function used by selectWindowRewriteEList(). If necessary,
745 ** this function appends to the output expression-list and updates
746 ** expression (*ppExpr) in place.
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 );
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;
768 if( i==nSrc ) return WRC_Continue;
772 switch( pExpr->op ){
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;
786 /* no break */ deliberate_fall_through
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;
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);
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));
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;
820 if( pParse->db->mallocFailed ) return WRC_Abort;
821 break;
824 default: /* no-op */
825 break;
828 return WRC_Continue;
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;
840 return WRC_Prune;
845 ** Iterate through each expression in expression-list pEList. For each:
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).
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.
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 */
865 Walker sWalker;
866 WindowRewrite sRewrite;
868 assert( pWin!=0 );
869 memset(&sWalker, 0, sizeof(Walker));
870 memset(&sRewrite, 0, sizeof(WindowRewrite));
872 sRewrite.pSub = *ppSub;
873 sRewrite.pWin = pWin;
874 sRewrite.pSrc = pSrc;
875 sRewrite.pTab = pTab;
877 sWalker.pParse = pParse;
878 sWalker.xExprCallback = selectWindowRewriteExprCb;
879 sWalker.xSelectCallback = selectWindowRewriteSelectCb;
880 sWalker.u.pRewrite = &sRewrite;
882 (void)sqlite3WalkExprList(&sWalker, pEList);
884 *ppSub = sRewrite.pSub;
888 ** Append a copy of each expression in expression-list pAppend to
889 ** expression list pList. Return a pointer to the result list.
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
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;
908 if( bIntToNull ){
909 int iDummy;
910 Expr *pSub;
911 for(pSub=pDup; ExprHasProperty(pSub, EP_Skip); pSub=pSub->pLeft){
912 assert( pSub );
914 if( sqlite3ExprIsInteger(pSub, &iDummy) ){
915 pSub->op = TK_NULL;
916 pSub->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
917 pSub->u.zToken = 0;
920 pList = sqlite3ExprListAppend(pParse, pList, pDup);
921 if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;
924 return pList;
928 ** When rewriting a query, if the new subquery in the FROM clause
929 ** contains TK_AGG_FUNCTION nodes that refer to an outer query,
930 ** then we have to increase the Expr->op2 values of those nodes
931 ** due to the extra subquery layer that was added.
933 ** See also the incrAggDepth() routine in resolve.c
935 static int sqlite3WindowExtraAggFuncDepth(Walker *pWalker, Expr *pExpr){
936 if( pExpr->op==TK_AGG_FUNCTION
937 && pExpr->op2>=pWalker->walkerDepth
939 pExpr->op2++;
941 return WRC_Continue;
944 static int disallowAggregatesInOrderByCb(Walker *pWalker, Expr *pExpr){
945 if( pExpr->op==TK_AGG_FUNCTION && pExpr->pAggInfo==0 ){
946 sqlite3ErrorMsg(pWalker->pParse,
947 "misuse of aggregate: %s()", pExpr->u.zToken);
949 return WRC_Continue;
953 ** If the SELECT statement passed as the second argument does not invoke
954 ** any SQL window functions, this function is a no-op. Otherwise, it
955 ** rewrites the SELECT statement so that window function xStep functions
956 ** are invoked in the correct order as described under "SELECT REWRITING"
957 ** at the top of this file.
959 int sqlite3WindowRewrite(Parse *pParse, Select *p){
960 int rc = SQLITE_OK;
961 if( p->pWin && p->pPrior==0 && ALWAYS((p->selFlags & SF_WinRewrite)==0) ){
962 Vdbe *v = sqlite3GetVdbe(pParse);
963 sqlite3 *db = pParse->db;
964 Select *pSub = 0; /* The subquery */
965 SrcList *pSrc = p->pSrc;
966 Expr *pWhere = p->pWhere;
967 ExprList *pGroupBy = p->pGroupBy;
968 Expr *pHaving = p->pHaving;
969 ExprList *pSort = 0;
971 ExprList *pSublist = 0; /* Expression list for sub-query */
972 Window *pMWin = p->pWin; /* Main window object */
973 Window *pWin; /* Window object iterator */
974 Table *pTab;
975 Walker w;
977 u32 selFlags = p->selFlags;
979 pTab = sqlite3DbMallocZero(db, sizeof(Table));
980 if( pTab==0 ){
981 return sqlite3ErrorToParser(db, SQLITE_NOMEM);
983 sqlite3AggInfoPersistWalkerInit(&w, pParse);
984 sqlite3WalkSelect(&w, p);
985 if( (p->selFlags & SF_Aggregate)==0 ){
986 w.xExprCallback = disallowAggregatesInOrderByCb;
987 w.xSelectCallback = 0;
988 sqlite3WalkExprList(&w, p->pOrderBy);
991 p->pSrc = 0;
992 p->pWhere = 0;
993 p->pGroupBy = 0;
994 p->pHaving = 0;
995 p->selFlags &= ~SF_Aggregate;
996 p->selFlags |= SF_WinRewrite;
998 /* Create the ORDER BY clause for the sub-select. This is the concatenation
999 ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
1000 ** redundant, remove the ORDER BY from the parent SELECT. */
1001 pSort = exprListAppendList(pParse, 0, pMWin->pPartition, 1);
1002 pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);
1003 if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){
1004 int nSave = pSort->nExpr;
1005 pSort->nExpr = p->pOrderBy->nExpr;
1006 if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
1007 sqlite3ExprListDelete(db, p->pOrderBy);
1008 p->pOrderBy = 0;
1010 pSort->nExpr = nSave;
1013 /* Assign a cursor number for the ephemeral table used to buffer rows.
1014 ** The OpenEphemeral instruction is coded later, after it is known how
1015 ** many columns the table will have. */
1016 pMWin->iEphCsr = pParse->nTab++;
1017 pParse->nTab += 3;
1019 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);
1020 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);
1021 pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
1023 /* Append the PARTITION BY and ORDER BY expressions to the to the
1024 ** sub-select expression list. They are required to figure out where
1025 ** boundaries for partitions and sets of peer rows lie. */
1026 pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);
1027 pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);
1029 /* Append the arguments passed to each window function to the
1030 ** sub-select expression list. Also allocate two registers for each
1031 ** window function - one for the accumulator, another for interim
1032 ** results. */
1033 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1034 ExprList *pArgs = pWin->pOwner->x.pList;
1035 if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){
1036 selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);
1037 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
1038 pWin->bExprArgs = 1;
1039 }else{
1040 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
1041 pSublist = exprListAppendList(pParse, pSublist, pArgs, 0);
1043 if( pWin->pFilter ){
1044 Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
1045 pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
1047 pWin->regAccum = ++pParse->nMem;
1048 pWin->regResult = ++pParse->nMem;
1049 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1052 /* If there is no ORDER BY or PARTITION BY clause, and the window
1053 ** function accepts zero arguments, and there are no other columns
1054 ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
1055 ** that pSublist is still NULL here. Add a constant expression here to
1056 ** keep everything legal in this case.
1058 if( pSublist==0 ){
1059 pSublist = sqlite3ExprListAppend(pParse, 0,
1060 sqlite3Expr(db, TK_INTEGER, "0")
1064 pSub = sqlite3SelectNew(
1065 pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
1067 SELECTTRACE(1,pParse,pSub,
1068 ("New window-function subquery in FROM clause of (%u/%p)\n",
1069 p->selId, p));
1070 p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
1071 if( p->pSrc ){
1072 Table *pTab2;
1073 p->pSrc->a[0].pSelect = pSub;
1074 sqlite3SrcListAssignCursors(pParse, p->pSrc);
1075 pSub->selFlags |= SF_Expanded;
1076 pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);
1077 pSub->selFlags |= (selFlags & SF_Aggregate);
1078 if( pTab2==0 ){
1079 /* Might actually be some other kind of error, but in that case
1080 ** pParse->nErr will be set, so if SQLITE_NOMEM is set, we will get
1081 ** the correct error message regardless. */
1082 rc = SQLITE_NOMEM;
1083 }else{
1084 memcpy(pTab, pTab2, sizeof(Table));
1085 pTab->tabFlags |= TF_Ephemeral;
1086 p->pSrc->a[0].pTab = pTab;
1087 pTab = pTab2;
1088 memset(&w, 0, sizeof(w));
1089 w.xExprCallback = sqlite3WindowExtraAggFuncDepth;
1090 w.xSelectCallback = sqlite3WalkerDepthIncrease;
1091 w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
1092 sqlite3WalkSelect(&w, pSub);
1094 }else{
1095 sqlite3SelectDelete(db, pSub);
1097 if( db->mallocFailed ) rc = SQLITE_NOMEM;
1098 sqlite3DbFree(db, pTab);
1101 if( rc ){
1102 if( pParse->nErr==0 ){
1103 assert( pParse->db->mallocFailed );
1104 sqlite3ErrorToParser(pParse->db, SQLITE_NOMEM);
1107 return rc;
1111 ** Unlink the Window object from the Select to which it is attached,
1112 ** if it is attached.
1114 void sqlite3WindowUnlinkFromSelect(Window *p){
1115 if( p->ppThis ){
1116 *p->ppThis = p->pNextWin;
1117 if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis;
1118 p->ppThis = 0;
1123 ** Free the Window object passed as the second argument.
1125 void sqlite3WindowDelete(sqlite3 *db, Window *p){
1126 if( p ){
1127 sqlite3WindowUnlinkFromSelect(p);
1128 sqlite3ExprDelete(db, p->pFilter);
1129 sqlite3ExprListDelete(db, p->pPartition);
1130 sqlite3ExprListDelete(db, p->pOrderBy);
1131 sqlite3ExprDelete(db, p->pEnd);
1132 sqlite3ExprDelete(db, p->pStart);
1133 sqlite3DbFree(db, p->zName);
1134 sqlite3DbFree(db, p->zBase);
1135 sqlite3DbFree(db, p);
1140 ** Free the linked list of Window objects starting at the second argument.
1142 void sqlite3WindowListDelete(sqlite3 *db, Window *p){
1143 while( p ){
1144 Window *pNext = p->pNextWin;
1145 sqlite3WindowDelete(db, p);
1146 p = pNext;
1151 ** The argument expression is an PRECEDING or FOLLOWING offset. The
1152 ** value should be a non-negative integer. If the value is not a
1153 ** constant, change it to NULL. The fact that it is then a non-negative
1154 ** integer will be caught later. But it is important not to leave
1155 ** variable values in the expression tree.
1157 static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
1158 if( 0==sqlite3ExprIsConstant(pExpr) ){
1159 if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
1160 sqlite3ExprDelete(pParse->db, pExpr);
1161 pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
1163 return pExpr;
1167 ** Allocate and return a new Window object describing a Window Definition.
1169 Window *sqlite3WindowAlloc(
1170 Parse *pParse, /* Parsing context */
1171 int eType, /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */
1172 int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
1173 Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */
1174 int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
1175 Expr *pEnd, /* End window size if TK_FOLLOWING or PRECEDING */
1176 u8 eExclude /* EXCLUDE clause */
1178 Window *pWin = 0;
1179 int bImplicitFrame = 0;
1181 /* Parser assures the following: */
1182 assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
1183 assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
1184 || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
1185 assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
1186 || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
1187 assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
1188 assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
1190 if( eType==0 ){
1191 bImplicitFrame = 1;
1192 eType = TK_RANGE;
1195 /* Additionally, the
1196 ** starting boundary type may not occur earlier in the following list than
1197 ** the ending boundary type:
1199 ** UNBOUNDED PRECEDING
1200 ** <expr> PRECEDING
1201 ** CURRENT ROW
1202 ** <expr> FOLLOWING
1203 ** UNBOUNDED FOLLOWING
1205 ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
1206 ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
1207 ** frame boundary.
1209 if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
1210 || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
1212 sqlite3ErrorMsg(pParse, "unsupported frame specification");
1213 goto windowAllocErr;
1216 pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
1217 if( pWin==0 ) goto windowAllocErr;
1218 pWin->eFrmType = eType;
1219 pWin->eStart = eStart;
1220 pWin->eEnd = eEnd;
1221 if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){
1222 eExclude = TK_NO;
1224 pWin->eExclude = eExclude;
1225 pWin->bImplicitFrame = bImplicitFrame;
1226 pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
1227 pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
1228 return pWin;
1230 windowAllocErr:
1231 sqlite3ExprDelete(pParse->db, pEnd);
1232 sqlite3ExprDelete(pParse->db, pStart);
1233 return 0;
1237 ** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
1238 ** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
1239 ** equivalent nul-terminated string.
1241 Window *sqlite3WindowAssemble(
1242 Parse *pParse,
1243 Window *pWin,
1244 ExprList *pPartition,
1245 ExprList *pOrderBy,
1246 Token *pBase
1248 if( pWin ){
1249 pWin->pPartition = pPartition;
1250 pWin->pOrderBy = pOrderBy;
1251 if( pBase ){
1252 pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
1254 }else{
1255 sqlite3ExprListDelete(pParse->db, pPartition);
1256 sqlite3ExprListDelete(pParse->db, pOrderBy);
1258 return pWin;
1262 ** Window *pWin has just been created from a WINDOW clause. Tokne pBase
1263 ** is the base window. Earlier windows from the same WINDOW clause are
1264 ** stored in the linked list starting at pWin->pNextWin. This function
1265 ** either updates *pWin according to the base specification, or else
1266 ** leaves an error in pParse.
1268 void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
1269 if( pWin->zBase ){
1270 sqlite3 *db = pParse->db;
1271 Window *pExist = windowFind(pParse, pList, pWin->zBase);
1272 if( pExist ){
1273 const char *zErr = 0;
1274 /* Check for errors */
1275 if( pWin->pPartition ){
1276 zErr = "PARTITION clause";
1277 }else if( pExist->pOrderBy && pWin->pOrderBy ){
1278 zErr = "ORDER BY clause";
1279 }else if( pExist->bImplicitFrame==0 ){
1280 zErr = "frame specification";
1282 if( zErr ){
1283 sqlite3ErrorMsg(pParse,
1284 "cannot override %s of window: %s", zErr, pWin->zBase
1286 }else{
1287 pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
1288 if( pExist->pOrderBy ){
1289 assert( pWin->pOrderBy==0 );
1290 pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
1292 sqlite3DbFree(db, pWin->zBase);
1293 pWin->zBase = 0;
1300 ** Attach window object pWin to expression p.
1302 void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
1303 if( p ){
1304 assert( p->op==TK_FUNCTION );
1305 assert( pWin );
1306 p->y.pWin = pWin;
1307 ExprSetProperty(p, EP_WinFunc);
1308 pWin->pOwner = p;
1309 if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){
1310 sqlite3ErrorMsg(pParse,
1311 "DISTINCT is not supported for window functions"
1314 }else{
1315 sqlite3WindowDelete(pParse->db, pWin);
1320 ** Possibly link window pWin into the list at pSel->pWin (window functions
1321 ** to be processed as part of SELECT statement pSel). The window is linked
1322 ** in if either (a) there are no other windows already linked to this
1323 ** SELECT, or (b) the windows already linked use a compatible window frame.
1325 void sqlite3WindowLink(Select *pSel, Window *pWin){
1326 if( pSel ){
1327 if( 0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0) ){
1328 pWin->pNextWin = pSel->pWin;
1329 if( pSel->pWin ){
1330 pSel->pWin->ppThis = &pWin->pNextWin;
1332 pSel->pWin = pWin;
1333 pWin->ppThis = &pSel->pWin;
1334 }else{
1335 if( sqlite3ExprListCompare(pWin->pPartition, pSel->pWin->pPartition,-1) ){
1336 pSel->selFlags |= SF_MultiPart;
1343 ** Return 0 if the two window objects are identical, 1 if they are
1344 ** different, or 2 if it cannot be determined if the objects are identical
1345 ** or not. Identical window objects can be processed in a single scan.
1347 int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2, int bFilter){
1348 int res;
1349 if( NEVER(p1==0) || NEVER(p2==0) ) return 1;
1350 if( p1->eFrmType!=p2->eFrmType ) return 1;
1351 if( p1->eStart!=p2->eStart ) return 1;
1352 if( p1->eEnd!=p2->eEnd ) return 1;
1353 if( p1->eExclude!=p2->eExclude ) return 1;
1354 if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
1355 if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
1356 if( (res = sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1)) ){
1357 return res;
1359 if( (res = sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1)) ){
1360 return res;
1362 if( bFilter ){
1363 if( (res = sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1)) ){
1364 return res;
1367 return 0;
1372 ** This is called by code in select.c before it calls sqlite3WhereBegin()
1373 ** to begin iterating through the sub-query results. It is used to allocate
1374 ** and initialize registers and cursors used by sqlite3WindowCodeStep().
1376 void sqlite3WindowCodeInit(Parse *pParse, Select *pSelect){
1377 int nEphExpr = pSelect->pSrc->a[0].pSelect->pEList->nExpr;
1378 Window *pMWin = pSelect->pWin;
1379 Window *pWin;
1380 Vdbe *v = sqlite3GetVdbe(pParse);
1382 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr);
1383 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
1384 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
1385 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
1387 /* Allocate registers to use for PARTITION BY values, if any. Initialize
1388 ** said registers to NULL. */
1389 if( pMWin->pPartition ){
1390 int nExpr = pMWin->pPartition->nExpr;
1391 pMWin->regPart = pParse->nMem+1;
1392 pParse->nMem += nExpr;
1393 sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
1396 pMWin->regOne = ++pParse->nMem;
1397 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
1399 if( pMWin->eExclude ){
1400 pMWin->regStartRowid = ++pParse->nMem;
1401 pMWin->regEndRowid = ++pParse->nMem;
1402 pMWin->csrApp = pParse->nTab++;
1403 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
1404 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
1405 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
1406 return;
1409 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1410 FuncDef *p = pWin->pFunc;
1411 if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
1412 /* The inline versions of min() and max() require a single ephemeral
1413 ** table and 3 registers. The registers are used as follows:
1415 ** regApp+0: slot to copy min()/max() argument to for MakeRecord
1416 ** regApp+1: integer value used to ensure keys are unique
1417 ** regApp+2: output of MakeRecord
1419 ExprList *pList = pWin->pOwner->x.pList;
1420 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
1421 pWin->csrApp = pParse->nTab++;
1422 pWin->regApp = pParse->nMem+1;
1423 pParse->nMem += 3;
1424 if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
1425 assert( pKeyInfo->aSortFlags[0]==0 );
1426 pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC;
1428 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
1429 sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
1430 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1432 else if( p->zName==nth_valueName || p->zName==first_valueName ){
1433 /* Allocate two registers at pWin->regApp. These will be used to
1434 ** store the start and end index of the current frame. */
1435 pWin->regApp = pParse->nMem+1;
1436 pWin->csrApp = pParse->nTab++;
1437 pParse->nMem += 2;
1438 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1440 else if( p->zName==leadName || p->zName==lagName ){
1441 pWin->csrApp = pParse->nTab++;
1442 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1447 #define WINDOW_STARTING_INT 0
1448 #define WINDOW_ENDING_INT 1
1449 #define WINDOW_NTH_VALUE_INT 2
1450 #define WINDOW_STARTING_NUM 3
1451 #define WINDOW_ENDING_NUM 4
1454 ** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
1455 ** value of the second argument to nth_value() (eCond==2) has just been
1456 ** evaluated and the result left in register reg. This function generates VM
1457 ** code to check that the value is a non-negative integer and throws an
1458 ** exception if it is not.
1460 static void windowCheckValue(Parse *pParse, int reg, int eCond){
1461 static const char *azErr[] = {
1462 "frame starting offset must be a non-negative integer",
1463 "frame ending offset must be a non-negative integer",
1464 "second argument to nth_value must be a positive integer",
1465 "frame starting offset must be a non-negative number",
1466 "frame ending offset must be a non-negative number",
1468 static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };
1469 Vdbe *v = sqlite3GetVdbe(pParse);
1470 int regZero = sqlite3GetTempReg(pParse);
1471 assert( eCond>=0 && eCond<ArraySize(azErr) );
1472 sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
1473 if( eCond>=WINDOW_STARTING_NUM ){
1474 int regString = sqlite3GetTempReg(pParse);
1475 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
1476 sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);
1477 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL);
1478 VdbeCoverage(v);
1479 assert( eCond==3 || eCond==4 );
1480 VdbeCoverageIf(v, eCond==3);
1481 VdbeCoverageIf(v, eCond==4);
1482 }else{
1483 sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
1484 VdbeCoverage(v);
1485 assert( eCond==0 || eCond==1 || eCond==2 );
1486 VdbeCoverageIf(v, eCond==0);
1487 VdbeCoverageIf(v, eCond==1);
1488 VdbeCoverageIf(v, eCond==2);
1490 sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
1491 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC);
1492 VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */
1493 VdbeCoverageNeverNullIf(v, eCond==1); /* the OP_MustBeInt */
1494 VdbeCoverageNeverNullIf(v, eCond==2);
1495 VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */
1496 VdbeCoverageNeverNullIf(v, eCond==4); /* the OP_Ge */
1497 sqlite3MayAbort(pParse);
1498 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
1499 sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
1500 sqlite3ReleaseTempReg(pParse, regZero);
1504 ** Return the number of arguments passed to the window-function associated
1505 ** with the object passed as the only argument to this function.
1507 static int windowArgCount(Window *pWin){
1508 ExprList *pList = pWin->pOwner->x.pList;
1509 return (pList ? pList->nExpr : 0);
1512 typedef struct WindowCodeArg WindowCodeArg;
1513 typedef struct WindowCsrAndReg WindowCsrAndReg;
1516 ** See comments above struct WindowCodeArg.
1518 struct WindowCsrAndReg {
1519 int csr; /* Cursor number */
1520 int reg; /* First in array of peer values */
1524 ** A single instance of this structure is allocated on the stack by
1525 ** sqlite3WindowCodeStep() and a pointer to it passed to the various helper
1526 ** routines. This is to reduce the number of arguments required by each
1527 ** helper function.
1529 ** regArg:
1530 ** Each window function requires an accumulator register (just as an
1531 ** ordinary aggregate function does). This variable is set to the first
1532 ** in an array of accumulator registers - one for each window function
1533 ** in the WindowCodeArg.pMWin list.
1535 ** eDelete:
1536 ** The window functions implementation sometimes caches the input rows
1537 ** that it processes in a temporary table. If it is not zero, this
1538 ** variable indicates when rows may be removed from the temp table (in
1539 ** order to reduce memory requirements - it would always be safe just
1540 ** to leave them there). Possible values for eDelete are:
1542 ** WINDOW_RETURN_ROW:
1543 ** An input row can be discarded after it is returned to the caller.
1545 ** WINDOW_AGGINVERSE:
1546 ** An input row can be discarded after the window functions xInverse()
1547 ** callbacks have been invoked in it.
1549 ** WINDOW_AGGSTEP:
1550 ** An input row can be discarded after the window functions xStep()
1551 ** callbacks have been invoked in it.
1553 ** start,current,end
1554 ** Consider a window-frame similar to the following:
1556 ** (ORDER BY a, b GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING)
1558 ** The windows functions implmentation caches the input rows in a temp
1559 ** table, sorted by "a, b" (it actually populates the cache lazily, and
1560 ** aggressively removes rows once they are no longer required, but that's
1561 ** a mere detail). It keeps three cursors open on the temp table. One
1562 ** (current) that points to the next row to return to the query engine
1563 ** once its window function values have been calculated. Another (end)
1564 ** points to the next row to call the xStep() method of each window function
1565 ** on (so that it is 2 groups ahead of current). And a third (start) that
1566 ** points to the next row to call the xInverse() method of each window
1567 ** function on.
1569 ** Each cursor (start, current and end) consists of a VDBE cursor
1570 ** (WindowCsrAndReg.csr) and an array of registers (starting at
1571 ** WindowCodeArg.reg) that always contains a copy of the peer values
1572 ** read from the corresponding cursor.
1574 ** Depending on the window-frame in question, all three cursors may not
1575 ** be required. In this case both WindowCodeArg.csr and reg are set to
1576 ** 0.
1578 struct WindowCodeArg {
1579 Parse *pParse; /* Parse context */
1580 Window *pMWin; /* First in list of functions being processed */
1581 Vdbe *pVdbe; /* VDBE object */
1582 int addrGosub; /* OP_Gosub to this address to return one row */
1583 int regGosub; /* Register used with OP_Gosub(addrGosub) */
1584 int regArg; /* First in array of accumulator registers */
1585 int eDelete; /* See above */
1586 int regRowid;
1588 WindowCsrAndReg start;
1589 WindowCsrAndReg current;
1590 WindowCsrAndReg end;
1594 ** Generate VM code to read the window frames peer values from cursor csr into
1595 ** an array of registers starting at reg.
1597 static void windowReadPeerValues(
1598 WindowCodeArg *p,
1599 int csr,
1600 int reg
1602 Window *pMWin = p->pMWin;
1603 ExprList *pOrderBy = pMWin->pOrderBy;
1604 if( pOrderBy ){
1605 Vdbe *v = sqlite3GetVdbe(p->pParse);
1606 ExprList *pPart = pMWin->pPartition;
1607 int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
1608 int i;
1609 for(i=0; i<pOrderBy->nExpr; i++){
1610 sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
1616 ** Generate VM code to invoke either xStep() (if bInverse is 0) or
1617 ** xInverse (if bInverse is non-zero) for each window function in the
1618 ** linked list starting at pMWin. Or, for built-in window functions
1619 ** that do not use the standard function API, generate the required
1620 ** inline VM code.
1622 ** If argument csr is greater than or equal to 0, then argument reg is
1623 ** the first register in an array of registers guaranteed to be large
1624 ** enough to hold the array of arguments for each function. In this case
1625 ** the arguments are extracted from the current row of csr into the
1626 ** array of registers before invoking OP_AggStep or OP_AggInverse
1628 ** Or, if csr is less than zero, then the array of registers at reg is
1629 ** already populated with all columns from the current row of the sub-query.
1631 ** If argument regPartSize is non-zero, then it is a register containing the
1632 ** number of rows in the current partition.
1634 static void windowAggStep(
1635 WindowCodeArg *p,
1636 Window *pMWin, /* Linked list of window functions */
1637 int csr, /* Read arguments from this cursor */
1638 int bInverse, /* True to invoke xInverse instead of xStep */
1639 int reg /* Array of registers */
1641 Parse *pParse = p->pParse;
1642 Vdbe *v = sqlite3GetVdbe(pParse);
1643 Window *pWin;
1644 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1645 FuncDef *pFunc = pWin->pFunc;
1646 int regArg;
1647 int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin);
1648 int i;
1650 assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED );
1652 /* All OVER clauses in the same window function aggregate step must
1653 ** be the same. */
1654 assert( pWin==pMWin || sqlite3WindowCompare(pParse,pWin,pMWin,0)!=1 );
1656 for(i=0; i<nArg; i++){
1657 if( i!=1 || pFunc->zName!=nth_valueName ){
1658 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
1659 }else{
1660 sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
1663 regArg = reg;
1665 if( pMWin->regStartRowid==0
1666 && (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1667 && (pWin->eStart!=TK_UNBOUNDED)
1669 int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
1670 VdbeCoverage(v);
1671 if( bInverse==0 ){
1672 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
1673 sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
1674 sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
1675 sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
1676 }else{
1677 sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
1678 VdbeCoverageNeverTaken(v);
1679 sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
1680 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1682 sqlite3VdbeJumpHere(v, addrIsNull);
1683 }else if( pWin->regApp ){
1684 assert( pFunc->zName==nth_valueName
1685 || pFunc->zName==first_valueName
1687 assert( bInverse==0 || bInverse==1 );
1688 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
1689 }else if( pFunc->xSFunc!=noopStepFunc ){
1690 int addrIf = 0;
1691 if( pWin->pFilter ){
1692 int regTmp;
1693 assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr );
1694 assert( pWin->bExprArgs || nArg ||pWin->pOwner->x.pList==0 );
1695 regTmp = sqlite3GetTempReg(pParse);
1696 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
1697 addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
1698 VdbeCoverage(v);
1699 sqlite3ReleaseTempReg(pParse, regTmp);
1702 if( pWin->bExprArgs ){
1703 int iOp = sqlite3VdbeCurrentAddr(v);
1704 int iEnd;
1706 nArg = pWin->pOwner->x.pList->nExpr;
1707 regArg = sqlite3GetTempRange(pParse, nArg);
1708 sqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0);
1710 for(iEnd=sqlite3VdbeCurrentAddr(v); iOp<iEnd; iOp++){
1711 VdbeOp *pOp = sqlite3VdbeGetOp(v, iOp);
1712 if( pOp->opcode==OP_Column && pOp->p1==pWin->iEphCsr ){
1713 pOp->p1 = csr;
1717 if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
1718 CollSeq *pColl;
1719 assert( nArg>0 );
1720 pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
1721 sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
1723 sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
1724 bInverse, regArg, pWin->regAccum);
1725 sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
1726 sqlite3VdbeChangeP5(v, (u8)nArg);
1727 if( pWin->bExprArgs ){
1728 sqlite3ReleaseTempRange(pParse, regArg, nArg);
1730 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
1736 ** Values that may be passed as the second argument to windowCodeOp().
1738 #define WINDOW_RETURN_ROW 1
1739 #define WINDOW_AGGINVERSE 2
1740 #define WINDOW_AGGSTEP 3
1743 ** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
1744 ** (bFin==1) for each window function in the linked list starting at
1745 ** pMWin. Or, for built-in window-functions that do not use the standard
1746 ** API, generate the equivalent VM code.
1748 static void windowAggFinal(WindowCodeArg *p, int bFin){
1749 Parse *pParse = p->pParse;
1750 Window *pMWin = p->pMWin;
1751 Vdbe *v = sqlite3GetVdbe(pParse);
1752 Window *pWin;
1754 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1755 if( pMWin->regStartRowid==0
1756 && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1757 && (pWin->eStart!=TK_UNBOUNDED)
1759 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1760 sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
1761 VdbeCoverage(v);
1762 sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
1763 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1764 }else if( pWin->regApp ){
1765 assert( pMWin->regStartRowid==0 );
1766 }else{
1767 int nArg = windowArgCount(pWin);
1768 if( bFin ){
1769 sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
1770 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
1771 sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
1772 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1773 }else{
1774 sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
1775 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
1782 ** Generate code to calculate the current values of all window functions in the
1783 ** p->pMWin list by doing a full scan of the current window frame. Store the
1784 ** results in the Window.regResult registers, ready to return the upper
1785 ** layer.
1787 static void windowFullScan(WindowCodeArg *p){
1788 Window *pWin;
1789 Parse *pParse = p->pParse;
1790 Window *pMWin = p->pMWin;
1791 Vdbe *v = p->pVdbe;
1793 int regCRowid = 0; /* Current rowid value */
1794 int regCPeer = 0; /* Current peer values */
1795 int regRowid = 0; /* AggStep rowid value */
1796 int regPeer = 0; /* AggStep peer values */
1798 int nPeer;
1799 int lblNext;
1800 int lblBrk;
1801 int addrNext;
1802 int csr;
1804 VdbeModuleComment((v, "windowFullScan begin"));
1806 assert( pMWin!=0 );
1807 csr = pMWin->csrApp;
1808 nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
1810 lblNext = sqlite3VdbeMakeLabel(pParse);
1811 lblBrk = sqlite3VdbeMakeLabel(pParse);
1813 regCRowid = sqlite3GetTempReg(pParse);
1814 regRowid = sqlite3GetTempReg(pParse);
1815 if( nPeer ){
1816 regCPeer = sqlite3GetTempRange(pParse, nPeer);
1817 regPeer = sqlite3GetTempRange(pParse, nPeer);
1820 sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
1821 windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
1823 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1824 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1827 sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
1828 VdbeCoverage(v);
1829 addrNext = sqlite3VdbeCurrentAddr(v);
1830 sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);
1831 sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
1832 VdbeCoverageNeverNull(v);
1834 if( pMWin->eExclude==TK_CURRENT ){
1835 sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);
1836 VdbeCoverageNeverNull(v);
1837 }else if( pMWin->eExclude!=TK_NO ){
1838 int addr;
1839 int addrEq = 0;
1840 KeyInfo *pKeyInfo = 0;
1842 if( pMWin->pOrderBy ){
1843 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
1845 if( pMWin->eExclude==TK_TIES ){
1846 addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);
1847 VdbeCoverageNeverNull(v);
1849 if( pKeyInfo ){
1850 windowReadPeerValues(p, csr, regPeer);
1851 sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);
1852 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1853 addr = sqlite3VdbeCurrentAddr(v)+1;
1854 sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);
1855 VdbeCoverageEqNe(v);
1856 }else{
1857 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);
1859 if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);
1862 windowAggStep(p, pMWin, csr, 0, p->regArg);
1864 sqlite3VdbeResolveLabel(v, lblNext);
1865 sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);
1866 VdbeCoverage(v);
1867 sqlite3VdbeJumpHere(v, addrNext-1);
1868 sqlite3VdbeJumpHere(v, addrNext+1);
1869 sqlite3ReleaseTempReg(pParse, regRowid);
1870 sqlite3ReleaseTempReg(pParse, regCRowid);
1871 if( nPeer ){
1872 sqlite3ReleaseTempRange(pParse, regPeer, nPeer);
1873 sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);
1876 windowAggFinal(p, 1);
1877 VdbeModuleComment((v, "windowFullScan end"));
1881 ** Invoke the sub-routine at regGosub (generated by code in select.c) to
1882 ** return the current row of Window.iEphCsr. If all window functions are
1883 ** aggregate window functions that use the standard API, a single
1884 ** OP_Gosub instruction is all that this routine generates. Extra VM code
1885 ** for per-row processing is only generated for the following built-in window
1886 ** functions:
1888 ** nth_value()
1889 ** first_value()
1890 ** lag()
1891 ** lead()
1893 static void windowReturnOneRow(WindowCodeArg *p){
1894 Window *pMWin = p->pMWin;
1895 Vdbe *v = p->pVdbe;
1897 if( pMWin->regStartRowid ){
1898 windowFullScan(p);
1899 }else{
1900 Parse *pParse = p->pParse;
1901 Window *pWin;
1903 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1904 FuncDef *pFunc = pWin->pFunc;
1905 if( pFunc->zName==nth_valueName
1906 || pFunc->zName==first_valueName
1908 int csr = pWin->csrApp;
1909 int lbl = sqlite3VdbeMakeLabel(pParse);
1910 int tmpReg = sqlite3GetTempReg(pParse);
1911 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1913 if( pFunc->zName==nth_valueName ){
1914 sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
1915 windowCheckValue(pParse, tmpReg, 2);
1916 }else{
1917 sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
1919 sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
1920 sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
1921 VdbeCoverageNeverNull(v);
1922 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
1923 VdbeCoverageNeverTaken(v);
1924 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1925 sqlite3VdbeResolveLabel(v, lbl);
1926 sqlite3ReleaseTempReg(pParse, tmpReg);
1928 else if( pFunc->zName==leadName || pFunc->zName==lagName ){
1929 int nArg = pWin->pOwner->x.pList->nExpr;
1930 int csr = pWin->csrApp;
1931 int lbl = sqlite3VdbeMakeLabel(pParse);
1932 int tmpReg = sqlite3GetTempReg(pParse);
1933 int iEph = pMWin->iEphCsr;
1935 if( nArg<3 ){
1936 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1937 }else{
1938 sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
1940 sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
1941 if( nArg<2 ){
1942 int val = (pFunc->zName==leadName ? 1 : -1);
1943 sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
1944 }else{
1945 int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
1946 int tmpReg2 = sqlite3GetTempReg(pParse);
1947 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
1948 sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
1949 sqlite3ReleaseTempReg(pParse, tmpReg2);
1952 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
1953 VdbeCoverage(v);
1954 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1955 sqlite3VdbeResolveLabel(v, lbl);
1956 sqlite3ReleaseTempReg(pParse, tmpReg);
1960 sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
1964 ** Generate code to set the accumulator register for each window function
1965 ** in the linked list passed as the second argument to NULL. And perform
1966 ** any equivalent initialization required by any built-in window functions
1967 ** in the list.
1969 static int windowInitAccum(Parse *pParse, Window *pMWin){
1970 Vdbe *v = sqlite3GetVdbe(pParse);
1971 int regArg;
1972 int nArg = 0;
1973 Window *pWin;
1974 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1975 FuncDef *pFunc = pWin->pFunc;
1976 assert( pWin->regAccum );
1977 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1978 nArg = MAX(nArg, windowArgCount(pWin));
1979 if( pMWin->regStartRowid==0 ){
1980 if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
1981 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
1982 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1985 if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
1986 assert( pWin->eStart!=TK_UNBOUNDED );
1987 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
1988 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1992 regArg = pParse->nMem+1;
1993 pParse->nMem += nArg;
1994 return regArg;
1998 ** Return true if the current frame should be cached in the ephemeral table,
1999 ** even if there are no xInverse() calls required.
2001 static int windowCacheFrame(Window *pMWin){
2002 Window *pWin;
2003 if( pMWin->regStartRowid ) return 1;
2004 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
2005 FuncDef *pFunc = pWin->pFunc;
2006 if( (pFunc->zName==nth_valueName)
2007 || (pFunc->zName==first_valueName)
2008 || (pFunc->zName==leadName)
2009 || (pFunc->zName==lagName)
2011 return 1;
2014 return 0;
2018 ** regOld and regNew are each the first register in an array of size
2019 ** pOrderBy->nExpr. This function generates code to compare the two
2020 ** arrays of registers using the collation sequences and other comparison
2021 ** parameters specified by pOrderBy.
2023 ** If the two arrays are not equal, the contents of regNew is copied to
2024 ** regOld and control falls through. Otherwise, if the contents of the arrays
2025 ** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
2027 static void windowIfNewPeer(
2028 Parse *pParse,
2029 ExprList *pOrderBy,
2030 int regNew, /* First in array of new values */
2031 int regOld, /* First in array of old values */
2032 int addr /* Jump here */
2034 Vdbe *v = sqlite3GetVdbe(pParse);
2035 if( pOrderBy ){
2036 int nVal = pOrderBy->nExpr;
2037 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
2038 sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
2039 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
2040 sqlite3VdbeAddOp3(v, OP_Jump,
2041 sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
2043 VdbeCoverageEqNe(v);
2044 sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
2045 }else{
2046 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
2051 ** This function is called as part of generating VM programs for RANGE
2052 ** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
2053 ** the ORDER BY term in the window, and that argument op is OP_Ge, it generates
2054 ** code equivalent to:
2056 ** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
2058 ** The value of parameter op may also be OP_Gt or OP_Le. In these cases the
2059 ** operator in the above pseudo-code is replaced with ">" or "<=", respectively.
2061 ** If the sort-order for the ORDER BY term in the window is DESC, then the
2062 ** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is
2063 ** subtracted. And the comparison operator is inverted to - ">=" becomes "<=",
2064 ** ">" becomes "<", and so on. So, with DESC sort order, if the argument op
2065 ** is OP_Ge, the generated code is equivalent to:
2067 ** if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;
2069 ** A special type of arithmetic is used such that if csr1.peerVal is not
2070 ** a numeric type (real or integer), then the result of the addition
2071 ** or subtraction is a a copy of csr1.peerVal.
2073 static void windowCodeRangeTest(
2074 WindowCodeArg *p,
2075 int op, /* OP_Ge, OP_Gt, or OP_Le */
2076 int csr1, /* Cursor number for cursor 1 */
2077 int regVal, /* Register containing non-negative number */
2078 int csr2, /* Cursor number for cursor 2 */
2079 int lbl /* Jump destination if condition is true */
2081 Parse *pParse = p->pParse;
2082 Vdbe *v = sqlite3GetVdbe(pParse);
2083 ExprList *pOrderBy = p->pMWin->pOrderBy; /* ORDER BY clause for window */
2084 int reg1 = sqlite3GetTempReg(pParse); /* Reg. for csr1.peerVal+regVal */
2085 int reg2 = sqlite3GetTempReg(pParse); /* Reg. for csr2.peerVal */
2086 int regString = ++pParse->nMem; /* Reg. for constant value '' */
2087 int arith = OP_Add; /* OP_Add or OP_Subtract */
2088 int addrGe; /* Jump destination */
2089 int addrDone = sqlite3VdbeMakeLabel(pParse); /* Address past OP_Ge */
2090 CollSeq *pColl;
2092 /* Read the peer-value from each cursor into a register */
2093 windowReadPeerValues(p, csr1, reg1);
2094 windowReadPeerValues(p, csr2, reg2);
2096 assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
2097 assert( pOrderBy && pOrderBy->nExpr==1 );
2098 if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_DESC ){
2099 switch( op ){
2100 case OP_Ge: op = OP_Le; break;
2101 case OP_Gt: op = OP_Lt; break;
2102 default: assert( op==OP_Le ); op = OP_Ge; break;
2104 arith = OP_Subtract;
2107 VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl",
2108 reg1, (arith==OP_Add ? "+" : "-"), regVal,
2109 ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2
2112 /* If the BIGNULL flag is set for the ORDER BY, then it is required to
2113 ** consider NULL values to be larger than all other values, instead of
2114 ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this
2115 ** (and adding that capability causes a performance regression), so
2116 ** instead if the BIGNULL flag is set then cases where either reg1 or
2117 ** reg2 are NULL are handled separately in the following block. The code
2118 ** generated is equivalent to:
2120 ** if( reg1 IS NULL ){
2121 ** if( op==OP_Ge ) goto lbl;
2122 ** if( op==OP_Gt && reg2 IS NOT NULL ) goto lbl;
2123 ** if( op==OP_Le && reg2 IS NULL ) goto lbl;
2124 ** }else if( reg2 IS NULL ){
2125 ** if( op==OP_Le ) goto lbl;
2126 ** }
2128 ** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is
2129 ** not taken, control jumps over the comparison operator coded below this
2130 ** block. */
2131 if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_BIGNULL ){
2132 /* This block runs if reg1 contains a NULL. */
2133 int addr = sqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v);
2134 switch( op ){
2135 case OP_Ge:
2136 sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl);
2137 break;
2138 case OP_Gt:
2139 sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl);
2140 VdbeCoverage(v);
2141 break;
2142 case OP_Le:
2143 sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl);
2144 VdbeCoverage(v);
2145 break;
2146 default: assert( op==OP_Lt ); /* no-op */ break;
2148 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone);
2150 /* This block runs if reg1 is not NULL, but reg2 is. */
2151 sqlite3VdbeJumpHere(v, addr);
2152 sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); VdbeCoverage(v);
2153 if( op==OP_Gt || op==OP_Ge ){
2154 sqlite3VdbeChangeP2(v, -1, addrDone);
2158 /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).
2159 ** This block adds (or subtracts for DESC) the numeric value in regVal
2160 ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob),
2161 ** then leave reg1 as it is. In pseudo-code, this is implemented as:
2163 ** if( reg1>='' ) goto addrGe;
2164 ** reg1 = reg1 +/- regVal
2165 ** addrGe:
2167 ** Since all strings and blobs are greater-than-or-equal-to an empty string,
2168 ** the add/subtract is skipped for these, as required. If reg1 is a NULL,
2169 ** then the arithmetic is performed, but since adding or subtracting from
2170 ** NULL is always NULL anyway, this case is handled as required too. */
2171 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
2172 addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
2173 VdbeCoverage(v);
2174 if( (op==OP_Ge && arith==OP_Add) || (op==OP_Le && arith==OP_Subtract) ){
2175 sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
2177 sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
2178 sqlite3VdbeJumpHere(v, addrGe);
2180 /* Compare registers reg2 and reg1, taking the jump if required. Note that
2181 ** control skips over this test if the BIGNULL flag is set and either
2182 ** reg1 or reg2 contain a NULL value. */
2183 sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
2184 pColl = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[0].pExpr);
2185 sqlite3VdbeAppendP4(v, (void*)pColl, P4_COLLSEQ);
2186 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
2187 sqlite3VdbeResolveLabel(v, addrDone);
2189 assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
2190 testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);
2191 testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt);
2192 testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le);
2193 testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt);
2194 sqlite3ReleaseTempReg(pParse, reg1);
2195 sqlite3ReleaseTempReg(pParse, reg2);
2197 VdbeModuleComment((v, "CodeRangeTest: end"));
2201 ** Helper function for sqlite3WindowCodeStep(). Each call to this function
2202 ** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
2203 ** operation. Refer to the header comment for sqlite3WindowCodeStep() for
2204 ** details.
2206 static int windowCodeOp(
2207 WindowCodeArg *p, /* Context object */
2208 int op, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
2209 int regCountdown, /* Register for OP_IfPos countdown */
2210 int jumpOnEof /* Jump here if stepped cursor reaches EOF */
2212 int csr, reg;
2213 Parse *pParse = p->pParse;
2214 Window *pMWin = p->pMWin;
2215 int ret = 0;
2216 Vdbe *v = p->pVdbe;
2217 int addrContinue = 0;
2218 int bPeer = (pMWin->eFrmType!=TK_ROWS);
2220 int lblDone = sqlite3VdbeMakeLabel(pParse);
2221 int addrNextRange = 0;
2223 /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
2224 ** starts with UNBOUNDED PRECEDING. */
2225 if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
2226 assert( regCountdown==0 && jumpOnEof==0 );
2227 return 0;
2230 if( regCountdown>0 ){
2231 if( pMWin->eFrmType==TK_RANGE ){
2232 addrNextRange = sqlite3VdbeCurrentAddr(v);
2233 assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );
2234 if( op==WINDOW_AGGINVERSE ){
2235 if( pMWin->eStart==TK_FOLLOWING ){
2236 windowCodeRangeTest(
2237 p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
2239 }else{
2240 windowCodeRangeTest(
2241 p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
2244 }else{
2245 windowCodeRangeTest(
2246 p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
2249 }else{
2250 sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, lblDone, 1);
2251 VdbeCoverage(v);
2255 if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
2256 windowAggFinal(p, 0);
2258 addrContinue = sqlite3VdbeCurrentAddr(v);
2260 /* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or
2261 ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the
2262 ** start cursor does not advance past the end cursor within the
2263 ** temporary table. It otherwise might, if (a>b). Also ensure that,
2264 ** if the input cursor is still finding new rows, that the end
2265 ** cursor does not go past it to EOF. */
2266 if( pMWin->eStart==pMWin->eEnd && regCountdown
2267 && pMWin->eFrmType==TK_RANGE
2269 int regRowid1 = sqlite3GetTempReg(pParse);
2270 int regRowid2 = sqlite3GetTempReg(pParse);
2271 if( op==WINDOW_AGGINVERSE ){
2272 sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1);
2273 sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2);
2274 sqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1);
2275 VdbeCoverage(v);
2276 }else if( p->regRowid ){
2277 sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid1);
2278 sqlite3VdbeAddOp3(v, OP_Ge, p->regRowid, lblDone, regRowid1);
2279 VdbeCoverageNeverNull(v);
2281 sqlite3ReleaseTempReg(pParse, regRowid1);
2282 sqlite3ReleaseTempReg(pParse, regRowid2);
2283 assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING );
2286 switch( op ){
2287 case WINDOW_RETURN_ROW:
2288 csr = p->current.csr;
2289 reg = p->current.reg;
2290 windowReturnOneRow(p);
2291 break;
2293 case WINDOW_AGGINVERSE:
2294 csr = p->start.csr;
2295 reg = p->start.reg;
2296 if( pMWin->regStartRowid ){
2297 assert( pMWin->regEndRowid );
2298 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
2299 }else{
2300 windowAggStep(p, pMWin, csr, 1, p->regArg);
2302 break;
2304 default:
2305 assert( op==WINDOW_AGGSTEP );
2306 csr = p->end.csr;
2307 reg = p->end.reg;
2308 if( pMWin->regStartRowid ){
2309 assert( pMWin->regEndRowid );
2310 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
2311 }else{
2312 windowAggStep(p, pMWin, csr, 0, p->regArg);
2314 break;
2317 if( op==p->eDelete ){
2318 sqlite3VdbeAddOp1(v, OP_Delete, csr);
2319 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
2322 if( jumpOnEof ){
2323 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
2324 VdbeCoverage(v);
2325 ret = sqlite3VdbeAddOp0(v, OP_Goto);
2326 }else{
2327 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
2328 VdbeCoverage(v);
2329 if( bPeer ){
2330 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblDone);
2334 if( bPeer ){
2335 int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
2336 int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
2337 windowReadPeerValues(p, csr, regTmp);
2338 windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
2339 sqlite3ReleaseTempRange(pParse, regTmp, nReg);
2342 if( addrNextRange ){
2343 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
2345 sqlite3VdbeResolveLabel(v, lblDone);
2346 return ret;
2351 ** Allocate and return a duplicate of the Window object indicated by the
2352 ** third argument. Set the Window.pOwner field of the new object to
2353 ** pOwner.
2355 Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
2356 Window *pNew = 0;
2357 if( ALWAYS(p) ){
2358 pNew = sqlite3DbMallocZero(db, sizeof(Window));
2359 if( pNew ){
2360 pNew->zName = sqlite3DbStrDup(db, p->zName);
2361 pNew->zBase = sqlite3DbStrDup(db, p->zBase);
2362 pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
2363 pNew->pFunc = p->pFunc;
2364 pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
2365 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
2366 pNew->eFrmType = p->eFrmType;
2367 pNew->eEnd = p->eEnd;
2368 pNew->eStart = p->eStart;
2369 pNew->eExclude = p->eExclude;
2370 pNew->regResult = p->regResult;
2371 pNew->regAccum = p->regAccum;
2372 pNew->iArgCol = p->iArgCol;
2373 pNew->iEphCsr = p->iEphCsr;
2374 pNew->bExprArgs = p->bExprArgs;
2375 pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
2376 pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
2377 pNew->pOwner = pOwner;
2378 pNew->bImplicitFrame = p->bImplicitFrame;
2381 return pNew;
2385 ** Return a copy of the linked list of Window objects passed as the
2386 ** second argument.
2388 Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
2389 Window *pWin;
2390 Window *pRet = 0;
2391 Window **pp = &pRet;
2393 for(pWin=p; pWin; pWin=pWin->pNextWin){
2394 *pp = sqlite3WindowDup(db, 0, pWin);
2395 if( *pp==0 ) break;
2396 pp = &((*pp)->pNextWin);
2399 return pRet;
2403 ** Return true if it can be determined at compile time that expression
2404 ** pExpr evaluates to a value that, when cast to an integer, is greater
2405 ** than zero. False otherwise.
2407 ** If an OOM error occurs, this function sets the Parse.db.mallocFailed
2408 ** flag and returns zero.
2410 static int windowExprGtZero(Parse *pParse, Expr *pExpr){
2411 int ret = 0;
2412 sqlite3 *db = pParse->db;
2413 sqlite3_value *pVal = 0;
2414 sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);
2415 if( pVal && sqlite3_value_int(pVal)>0 ){
2416 ret = 1;
2418 sqlite3ValueFree(pVal);
2419 return ret;
2423 ** sqlite3WhereBegin() has already been called for the SELECT statement
2424 ** passed as the second argument when this function is invoked. It generates
2425 ** code to populate the Window.regResult register for each window function
2426 ** and invoke the sub-routine at instruction addrGosub once for each row.
2427 ** sqlite3WhereEnd() is always called before returning.
2429 ** This function handles several different types of window frames, which
2430 ** require slightly different processing. The following pseudo code is
2431 ** used to implement window frames of the form:
2433 ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
2435 ** Other window frame types use variants of the following:
2437 ** ... loop started by sqlite3WhereBegin() ...
2438 ** if( new partition ){
2439 ** Gosub flush
2440 ** }
2441 ** Insert new row into eph table.
2443 ** if( first row of partition ){
2444 ** // Rewind three cursors, all open on the eph table.
2445 ** Rewind(csrEnd);
2446 ** Rewind(csrStart);
2447 ** Rewind(csrCurrent);
2449 ** regEnd = <expr2> // FOLLOWING expression
2450 ** regStart = <expr1> // PRECEDING expression
2451 ** }else{
2452 ** // First time this branch is taken, the eph table contains two
2453 ** // rows. The first row in the partition, which all three cursors
2454 ** // currently point to, and the following row.
2455 ** AGGSTEP
2456 ** if( (regEnd--)<=0 ){
2457 ** RETURN_ROW
2458 ** if( (regStart--)<=0 ){
2459 ** AGGINVERSE
2460 ** }
2461 ** }
2462 ** }
2463 ** }
2464 ** flush:
2465 ** AGGSTEP
2466 ** while( 1 ){
2467 ** RETURN ROW
2468 ** if( csrCurrent is EOF ) break;
2469 ** if( (regStart--)<=0 ){
2470 ** AggInverse(csrStart)
2471 ** Next(csrStart)
2472 ** }
2473 ** }
2475 ** The pseudo-code above uses the following shorthand:
2477 ** AGGSTEP: invoke the aggregate xStep() function for each window function
2478 ** with arguments read from the current row of cursor csrEnd, then
2479 ** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
2481 ** RETURN_ROW: return a row to the caller based on the contents of the
2482 ** current row of csrCurrent and the current state of all
2483 ** aggregates. Then step cursor csrCurrent forward one row.
2485 ** AGGINVERSE: invoke the aggregate xInverse() function for each window
2486 ** functions with arguments read from the current row of cursor
2487 ** csrStart. Then step csrStart forward one row.
2489 ** There are two other ROWS window frames that are handled significantly
2490 ** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
2491 ** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
2492 ** cases because they change the order in which the three cursors (csrStart,
2493 ** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
2494 ** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
2495 ** three.
2497 ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2499 ** ... loop started by sqlite3WhereBegin() ...
2500 ** if( new partition ){
2501 ** Gosub flush
2502 ** }
2503 ** Insert new row into eph table.
2504 ** if( first row of partition ){
2505 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2506 ** regEnd = <expr2>
2507 ** regStart = <expr1>
2508 ** }else{
2509 ** if( (regEnd--)<=0 ){
2510 ** AGGSTEP
2511 ** }
2512 ** RETURN_ROW
2513 ** if( (regStart--)<=0 ){
2514 ** AGGINVERSE
2515 ** }
2516 ** }
2517 ** }
2518 ** flush:
2519 ** if( (regEnd--)<=0 ){
2520 ** AGGSTEP
2521 ** }
2522 ** RETURN_ROW
2525 ** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2527 ** ... loop started by sqlite3WhereBegin() ...
2528 ** if( new partition ){
2529 ** Gosub flush
2530 ** }
2531 ** Insert new row into eph table.
2532 ** if( first row of partition ){
2533 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2534 ** regEnd = <expr2>
2535 ** regStart = regEnd - <expr1>
2536 ** }else{
2537 ** AGGSTEP
2538 ** if( (regEnd--)<=0 ){
2539 ** RETURN_ROW
2540 ** }
2541 ** if( (regStart--)<=0 ){
2542 ** AGGINVERSE
2543 ** }
2544 ** }
2545 ** }
2546 ** flush:
2547 ** AGGSTEP
2548 ** while( 1 ){
2549 ** if( (regEnd--)<=0 ){
2550 ** RETURN_ROW
2551 ** if( eof ) break;
2552 ** }
2553 ** if( (regStart--)<=0 ){
2554 ** AGGINVERSE
2555 ** if( eof ) break
2556 ** }
2557 ** }
2558 ** while( !eof csrCurrent ){
2559 ** RETURN_ROW
2560 ** }
2562 ** For the most part, the patterns above are adapted to support UNBOUNDED by
2563 ** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
2564 ** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING".
2565 ** This is optimized of course - branches that will never be taken and
2566 ** conditions that are always true are omitted from the VM code. The only
2567 ** exceptional case is:
2569 ** ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
2571 ** ... loop started by sqlite3WhereBegin() ...
2572 ** if( new partition ){
2573 ** Gosub flush
2574 ** }
2575 ** Insert new row into eph table.
2576 ** if( first row of partition ){
2577 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2578 ** regStart = <expr1>
2579 ** }else{
2580 ** AGGSTEP
2581 ** }
2582 ** }
2583 ** flush:
2584 ** AGGSTEP
2585 ** while( 1 ){
2586 ** if( (regStart--)<=0 ){
2587 ** AGGINVERSE
2588 ** if( eof ) break
2589 ** }
2590 ** RETURN_ROW
2591 ** }
2592 ** while( !eof csrCurrent ){
2593 ** RETURN_ROW
2594 ** }
2596 ** Also requiring special handling are the cases:
2598 ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2599 ** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2601 ** when (expr1 < expr2). This is detected at runtime, not by this function.
2602 ** To handle this case, the pseudo-code programs depicted above are modified
2603 ** slightly to be:
2605 ** ... loop started by sqlite3WhereBegin() ...
2606 ** if( new partition ){
2607 ** Gosub flush
2608 ** }
2609 ** Insert new row into eph table.
2610 ** if( first row of partition ){
2611 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2612 ** regEnd = <expr2>
2613 ** regStart = <expr1>
2614 ** if( regEnd < regStart ){
2615 ** RETURN_ROW
2616 ** delete eph table contents
2617 ** continue
2618 ** }
2619 ** ...
2621 ** The new "continue" statement in the above jumps to the next iteration
2622 ** of the outer loop - the one started by sqlite3WhereBegin().
2624 ** The various GROUPS cases are implemented using the same patterns as
2625 ** ROWS. The VM code is modified slightly so that:
2627 ** 1. The else branch in the main loop is only taken if the row just
2628 ** added to the ephemeral table is the start of a new group. In
2629 ** other words, it becomes:
2631 ** ... loop started by sqlite3WhereBegin() ...
2632 ** if( new partition ){
2633 ** Gosub flush
2634 ** }
2635 ** Insert new row into eph table.
2636 ** if( first row of partition ){
2637 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2638 ** regEnd = <expr2>
2639 ** regStart = <expr1>
2640 ** }else if( new group ){
2641 ** ...
2642 ** }
2643 ** }
2645 ** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
2646 ** AGGINVERSE step processes the current row of the relevant cursor and
2647 ** all subsequent rows belonging to the same group.
2649 ** RANGE window frames are a little different again. As for GROUPS, the
2650 ** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
2651 ** deal in groups instead of rows. As for ROWS and GROUPS, there are three
2652 ** basic cases:
2654 ** RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
2656 ** ... loop started by sqlite3WhereBegin() ...
2657 ** if( new partition ){
2658 ** Gosub flush
2659 ** }
2660 ** Insert new row into eph table.
2661 ** if( first row of partition ){
2662 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2663 ** regEnd = <expr2>
2664 ** regStart = <expr1>
2665 ** }else{
2666 ** AGGSTEP
2667 ** while( (csrCurrent.key + regEnd) < csrEnd.key ){
2668 ** RETURN_ROW
2669 ** while( csrStart.key + regStart) < csrCurrent.key ){
2670 ** AGGINVERSE
2671 ** }
2672 ** }
2673 ** }
2674 ** }
2675 ** flush:
2676 ** AGGSTEP
2677 ** while( 1 ){
2678 ** RETURN ROW
2679 ** if( csrCurrent is EOF ) break;
2680 ** while( csrStart.key + regStart) < csrCurrent.key ){
2681 ** AGGINVERSE
2682 ** }
2683 ** }
2684 ** }
2686 ** In the above notation, "csr.key" means the current value of the ORDER BY
2687 ** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
2688 ** or <expr PRECEDING) read from cursor csr.
2690 ** RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2692 ** ... loop started by sqlite3WhereBegin() ...
2693 ** if( new partition ){
2694 ** Gosub flush
2695 ** }
2696 ** Insert new row into eph table.
2697 ** if( first row of partition ){
2698 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2699 ** regEnd = <expr2>
2700 ** regStart = <expr1>
2701 ** }else{
2702 ** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
2703 ** AGGSTEP
2704 ** }
2705 ** while( (csrStart.key + regStart) < csrCurrent.key ){
2706 ** AGGINVERSE
2707 ** }
2708 ** RETURN_ROW
2709 ** }
2710 ** }
2711 ** flush:
2712 ** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
2713 ** AGGSTEP
2714 ** }
2715 ** while( (csrStart.key + regStart) < csrCurrent.key ){
2716 ** AGGINVERSE
2717 ** }
2718 ** RETURN_ROW
2720 ** RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2722 ** ... loop started by sqlite3WhereBegin() ...
2723 ** if( new partition ){
2724 ** Gosub flush
2725 ** }
2726 ** Insert new row into eph table.
2727 ** if( first row of partition ){
2728 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2729 ** regEnd = <expr2>
2730 ** regStart = <expr1>
2731 ** }else{
2732 ** AGGSTEP
2733 ** while( (csrCurrent.key + regEnd) < csrEnd.key ){
2734 ** while( (csrCurrent.key + regStart) > csrStart.key ){
2735 ** AGGINVERSE
2736 ** }
2737 ** RETURN_ROW
2738 ** }
2739 ** }
2740 ** }
2741 ** flush:
2742 ** AGGSTEP
2743 ** while( 1 ){
2744 ** while( (csrCurrent.key + regStart) > csrStart.key ){
2745 ** AGGINVERSE
2746 ** if( eof ) break "while( 1 )" loop.
2747 ** }
2748 ** RETURN_ROW
2749 ** }
2750 ** while( !eof csrCurrent ){
2751 ** RETURN_ROW
2752 ** }
2754 ** The text above leaves out many details. Refer to the code and comments
2755 ** below for a more complete picture.
2757 void sqlite3WindowCodeStep(
2758 Parse *pParse, /* Parse context */
2759 Select *p, /* Rewritten SELECT statement */
2760 WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
2761 int regGosub, /* Register for OP_Gosub */
2762 int addrGosub /* OP_Gosub here to return each row */
2764 Window *pMWin = p->pWin;
2765 ExprList *pOrderBy = pMWin->pOrderBy;
2766 Vdbe *v = sqlite3GetVdbe(pParse);
2767 int csrWrite; /* Cursor used to write to eph. table */
2768 int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */
2769 int nInput = p->pSrc->a[0].pTab->nCol; /* Number of cols returned by sub */
2770 int iInput; /* To iterate through sub cols */
2771 int addrNe; /* Address of OP_Ne */
2772 int addrGosubFlush = 0; /* Address of OP_Gosub to flush: */
2773 int addrInteger = 0; /* Address of OP_Integer */
2774 int addrEmpty; /* Address of OP_Rewind in flush: */
2775 int regNew; /* Array of registers holding new input row */
2776 int regRecord; /* regNew array in record form */
2777 int regNewPeer = 0; /* Peer values for new row (part of regNew) */
2778 int regPeer = 0; /* Peer values for current row */
2779 int regFlushPart = 0; /* Register for "Gosub flush_partition" */
2780 WindowCodeArg s; /* Context object for sub-routines */
2781 int lblWhereEnd; /* Label just before sqlite3WhereEnd() code */
2782 int regStart = 0; /* Value of <expr> PRECEDING */
2783 int regEnd = 0; /* Value of <expr> FOLLOWING */
2785 assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
2786 || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
2788 assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
2789 || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
2791 assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
2792 || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
2793 || pMWin->eExclude==TK_NO
2796 lblWhereEnd = sqlite3VdbeMakeLabel(pParse);
2798 /* Fill in the context object */
2799 memset(&s, 0, sizeof(WindowCodeArg));
2800 s.pParse = pParse;
2801 s.pMWin = pMWin;
2802 s.pVdbe = v;
2803 s.regGosub = regGosub;
2804 s.addrGosub = addrGosub;
2805 s.current.csr = pMWin->iEphCsr;
2806 csrWrite = s.current.csr+1;
2807 s.start.csr = s.current.csr+2;
2808 s.end.csr = s.current.csr+3;
2810 /* Figure out when rows may be deleted from the ephemeral table. There
2811 ** are four options - they may never be deleted (eDelete==0), they may
2812 ** be deleted as soon as they are no longer part of the window frame
2813 ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
2814 ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
2815 ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
2816 switch( pMWin->eStart ){
2817 case TK_FOLLOWING:
2818 if( pMWin->eFrmType!=TK_RANGE
2819 && windowExprGtZero(pParse, pMWin->pStart)
2821 s.eDelete = WINDOW_RETURN_ROW;
2823 break;
2824 case TK_UNBOUNDED:
2825 if( windowCacheFrame(pMWin)==0 ){
2826 if( pMWin->eEnd==TK_PRECEDING ){
2827 if( pMWin->eFrmType!=TK_RANGE
2828 && windowExprGtZero(pParse, pMWin->pEnd)
2830 s.eDelete = WINDOW_AGGSTEP;
2832 }else{
2833 s.eDelete = WINDOW_RETURN_ROW;
2836 break;
2837 default:
2838 s.eDelete = WINDOW_AGGINVERSE;
2839 break;
2842 /* Allocate registers for the array of values from the sub-query, the
2843 ** samve values in record form, and the rowid used to insert said record
2844 ** into the ephemeral table. */
2845 regNew = pParse->nMem+1;
2846 pParse->nMem += nInput;
2847 regRecord = ++pParse->nMem;
2848 s.regRowid = ++pParse->nMem;
2850 /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
2851 ** clause, allocate registers to store the results of evaluating each
2852 ** <expr>. */
2853 if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
2854 regStart = ++pParse->nMem;
2856 if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
2857 regEnd = ++pParse->nMem;
2860 /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
2861 ** registers to store copies of the ORDER BY expressions (peer values)
2862 ** for the main loop, and for each cursor (start, current and end). */
2863 if( pMWin->eFrmType!=TK_ROWS ){
2864 int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
2865 regNewPeer = regNew + pMWin->nBufferCol;
2866 if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
2867 regPeer = pParse->nMem+1; pParse->nMem += nPeer;
2868 s.start.reg = pParse->nMem+1; pParse->nMem += nPeer;
2869 s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
2870 s.end.reg = pParse->nMem+1; pParse->nMem += nPeer;
2873 /* Load the column values for the row returned by the sub-select
2874 ** into an array of registers starting at regNew. Assemble them into
2875 ** a record in register regRecord. */
2876 for(iInput=0; iInput<nInput; iInput++){
2877 sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
2879 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
2881 /* An input row has just been read into an array of registers starting
2882 ** at regNew. If the window has a PARTITION clause, this block generates
2883 ** VM code to check if the input row is the start of a new partition.
2884 ** If so, it does an OP_Gosub to an address to be filled in later. The
2885 ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
2886 if( pMWin->pPartition ){
2887 int addr;
2888 ExprList *pPart = pMWin->pPartition;
2889 int nPart = pPart->nExpr;
2890 int regNewPart = regNew + pMWin->nBufferCol;
2891 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
2893 regFlushPart = ++pParse->nMem;
2894 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
2895 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
2896 sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
2897 VdbeCoverageEqNe(v);
2898 addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
2899 VdbeComment((v, "call flush_partition"));
2900 sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
2903 /* Insert the new row into the ephemeral table */
2904 sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, s.regRowid);
2905 sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, s.regRowid);
2906 addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, s.regRowid);
2907 VdbeCoverageNeverNull(v);
2909 /* This block is run for the first row of each partition */
2910 s.regArg = windowInitAccum(pParse, pMWin);
2912 if( regStart ){
2913 sqlite3ExprCode(pParse, pMWin->pStart, regStart);
2914 windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE?3:0));
2916 if( regEnd ){
2917 sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
2918 windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE?3:0));
2921 if( pMWin->eFrmType!=TK_RANGE && pMWin->eStart==pMWin->eEnd && regStart ){
2922 int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
2923 int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
2924 VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */
2925 VdbeCoverageNeverNullIf(v, op==OP_Le); /* values previously checked */
2926 windowAggFinal(&s, 0);
2927 sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
2928 VdbeCoverageNeverTaken(v);
2929 windowReturnOneRow(&s);
2930 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
2931 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
2932 sqlite3VdbeJumpHere(v, addrGe);
2934 if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){
2935 assert( pMWin->eEnd==TK_FOLLOWING );
2936 sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
2939 if( pMWin->eStart!=TK_UNBOUNDED ){
2940 sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1);
2941 VdbeCoverageNeverTaken(v);
2943 sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
2944 VdbeCoverageNeverTaken(v);
2945 sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1);
2946 VdbeCoverageNeverTaken(v);
2947 if( regPeer && pOrderBy ){
2948 sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
2949 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
2950 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
2951 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
2954 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
2956 sqlite3VdbeJumpHere(v, addrNe);
2958 /* Beginning of the block executed for the second and subsequent rows. */
2959 if( regPeer ){
2960 windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);
2962 if( pMWin->eStart==TK_FOLLOWING ){
2963 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
2964 if( pMWin->eEnd!=TK_UNBOUNDED ){
2965 if( pMWin->eFrmType==TK_RANGE ){
2966 int lbl = sqlite3VdbeMakeLabel(pParse);
2967 int addrNext = sqlite3VdbeCurrentAddr(v);
2968 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2969 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2970 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2971 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
2972 sqlite3VdbeResolveLabel(v, lbl);
2973 }else{
2974 windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
2975 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2978 }else
2979 if( pMWin->eEnd==TK_PRECEDING ){
2980 int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
2981 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
2982 if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2983 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2984 if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2985 }else{
2986 int addr = 0;
2987 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
2988 if( pMWin->eEnd!=TK_UNBOUNDED ){
2989 if( pMWin->eFrmType==TK_RANGE ){
2990 int lbl = 0;
2991 addr = sqlite3VdbeCurrentAddr(v);
2992 if( regEnd ){
2993 lbl = sqlite3VdbeMakeLabel(pParse);
2994 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2996 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2997 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2998 if( regEnd ){
2999 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
3000 sqlite3VdbeResolveLabel(v, lbl);
3002 }else{
3003 if( regEnd ){
3004 addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
3005 VdbeCoverage(v);
3007 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
3008 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
3009 if( regEnd ) sqlite3VdbeJumpHere(v, addr);
3014 /* End of the main input loop */
3015 sqlite3VdbeResolveLabel(v, lblWhereEnd);
3016 sqlite3WhereEnd(pWInfo);
3018 /* Fall through */
3019 if( pMWin->pPartition ){
3020 addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
3021 sqlite3VdbeJumpHere(v, addrGosubFlush);
3024 s.regRowid = 0;
3025 addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
3026 VdbeCoverage(v);
3027 if( pMWin->eEnd==TK_PRECEDING ){
3028 int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
3029 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
3030 if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
3031 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
3032 }else if( pMWin->eStart==TK_FOLLOWING ){
3033 int addrStart;
3034 int addrBreak1;
3035 int addrBreak2;
3036 int addrBreak3;
3037 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
3038 if( pMWin->eFrmType==TK_RANGE ){
3039 addrStart = sqlite3VdbeCurrentAddr(v);
3040 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
3041 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
3042 }else
3043 if( pMWin->eEnd==TK_UNBOUNDED ){
3044 addrStart = sqlite3VdbeCurrentAddr(v);
3045 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
3046 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
3047 }else{
3048 assert( pMWin->eEnd==TK_FOLLOWING );
3049 addrStart = sqlite3VdbeCurrentAddr(v);
3050 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
3051 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
3053 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
3054 sqlite3VdbeJumpHere(v, addrBreak2);
3055 addrStart = sqlite3VdbeCurrentAddr(v);
3056 addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
3057 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
3058 sqlite3VdbeJumpHere(v, addrBreak1);
3059 sqlite3VdbeJumpHere(v, addrBreak3);
3060 }else{
3061 int addrBreak;
3062 int addrStart;
3063 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
3064 addrStart = sqlite3VdbeCurrentAddr(v);
3065 addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
3066 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
3067 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
3068 sqlite3VdbeJumpHere(v, addrBreak);
3070 sqlite3VdbeJumpHere(v, addrEmpty);
3072 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
3073 if( pMWin->pPartition ){
3074 if( pMWin->regStartRowid ){
3075 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
3076 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
3078 sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
3079 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
3083 #endif /* SQLITE_OMIT_WINDOWFUNC */