4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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
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
26 ** CREATE TABLE t1(a, b, c, d, e, f, g);
30 ** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e;
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
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
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)
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)
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
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
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:
112 ** lead(expr [, offset [, default]])
113 ** lag(expr [, offset [, default]])
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 functions) 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
,
150 sqlite3_value
**apArg
152 i64
*p
= (i64
*)sqlite3_aggregate_context(pCtx
, sizeof(*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
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
,
181 sqlite3_value
**apArg
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
){
191 p
= (struct CallCount
*)sqlite3_aggregate_context(pCtx
, sizeof(*p
));
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".
208 sqlite3_value
*pValue
;
210 static void nth_valueStepFunc(
211 sqlite3_context
*pCtx
,
213 sqlite3_value
**apArg
215 struct NthValueCtx
*p
;
216 p
= (struct NthValueCtx
*)sqlite3_aggregate_context(pCtx
, sizeof(*p
));
219 switch( sqlite3_value_numeric_type(apArg
[1]) ){
221 iVal
= sqlite3_value_int64(apArg
[1]);
224 double fVal
= sqlite3_value_double(apArg
[1]);
225 if( ((i64
)fVal
)!=fVal
) goto error_out
;
232 if( iVal
<=0 ) goto error_out
;
235 if( iVal
==p
->nStep
){
236 p
->pValue
= sqlite3_value_dup(apArg
[0]);
238 sqlite3_result_error_nomem(pCtx
);
242 UNUSED_PARAMETER(nArg
);
243 UNUSED_PARAMETER(apArg
);
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
);
260 #define nth_valueInvFunc noopStepFunc
261 #define nth_valueValueFunc noopValueFunc
263 static void first_valueStepFunc(
264 sqlite3_context
*pCtx
,
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]);
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
);
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
,
300 sqlite3_value
**apArg
303 p
= (struct CallCount
*)sqlite3_aggregate_context(pCtx
, sizeof(*p
));
307 p
->nValue
= p
->nStep
;
310 UNUSED_PARAMETER(nArg
);
311 UNUSED_PARAMETER(apArg
);
313 static void rankValueFunc(sqlite3_context
*pCtx
){
315 p
= (struct CallCount
*)sqlite3_aggregate_context(pCtx
, sizeof(*p
));
317 sqlite3_result_int64(pCtx
, p
->nValue
);
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
,
331 sqlite3_value
**apArg
334 UNUSED_PARAMETER(nArg
); assert( nArg
==0 );
335 UNUSED_PARAMETER(apArg
);
336 p
= (struct CallCount
*)sqlite3_aggregate_context(pCtx
, sizeof(*p
));
341 static void percent_rankInvFunc(
342 sqlite3_context
*pCtx
,
344 sqlite3_value
**apArg
347 UNUSED_PARAMETER(nArg
); assert( nArg
==0 );
348 UNUSED_PARAMETER(apArg
);
349 p
= (struct CallCount
*)sqlite3_aggregate_context(pCtx
, sizeof(*p
));
352 static void percent_rankValueFunc(sqlite3_context
*pCtx
){
354 p
= (struct CallCount
*)sqlite3_aggregate_context(pCtx
, sizeof(*p
));
356 p
->nValue
= p
->nStep
;
358 double r
= (double)p
->nValue
/ (double)(p
->nTotal
-1);
359 sqlite3_result_double(pCtx
, r
);
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
,
376 sqlite3_value
**apArg
379 UNUSED_PARAMETER(nArg
); assert( nArg
==0 );
380 UNUSED_PARAMETER(apArg
);
381 p
= (struct CallCount
*)sqlite3_aggregate_context(pCtx
, sizeof(*p
));
386 static void cume_distInvFunc(
387 sqlite3_context
*pCtx
,
389 sqlite3_value
**apArg
392 UNUSED_PARAMETER(nArg
); assert( nArg
==0 );
393 UNUSED_PARAMETER(apArg
);
394 p
= (struct CallCount
*)sqlite3_aggregate_context(pCtx
, sizeof(*p
));
397 static void cume_distValueFunc(sqlite3_context
*pCtx
){
399 p
= (struct CallCount
*)sqlite3_aggregate_context(pCtx
, 0);
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.
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
420 ** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING
422 static void ntileStepFunc(
423 sqlite3_context
*pCtx
,
425 sqlite3_value
**apArg
428 assert( nArg
==1 ); UNUSED_PARAMETER(nArg
);
429 p
= (struct NtileCtx
*)sqlite3_aggregate_context(pCtx
, sizeof(*p
));
432 p
->nParam
= sqlite3_value_int64(apArg
[0]);
434 sqlite3_result_error(
435 pCtx
, "argument of ntile must be a positive integer", -1
442 static void ntileInvFunc(
443 sqlite3_context
*pCtx
,
445 sqlite3_value
**apArg
448 assert( nArg
==1 ); UNUSED_PARAMETER(nArg
);
449 UNUSED_PARAMETER(apArg
);
450 p
= (struct NtileCtx
*)sqlite3_aggregate_context(pCtx
, sizeof(*p
));
453 static void ntileValueFunc(sqlite3_context
*pCtx
){
455 p
= (struct NtileCtx
*)sqlite3_aggregate_context(pCtx
, sizeof(*p
));
456 if( p
&& p
->nParam
>0 ){
457 int nSize
= (p
->nTotal
/ p
->nParam
);
459 sqlite3_result_int64(pCtx
, p
->iRow
+1);
461 i64 nLarge
= p
->nTotal
- p
->nParam
*nSize
;
462 i64 iSmall
= nLarge
*(nSize
+1);
465 assert( (nLarge
*(nSize
+1) + (p
->nParam
-nLarge
)*nSize
)==p
->nTotal
);
468 sqlite3_result_int64(pCtx
, 1 + iRow
/(nSize
+1));
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
{
486 ** Implementation of last_value().
488 static void last_valueStepFunc(
489 sqlite3_context
*pCtx
,
491 sqlite3_value
**apArg
493 struct LastValueCtx
*p
;
494 UNUSED_PARAMETER(nArg
);
495 p
= (struct LastValueCtx
*)sqlite3_aggregate_context(pCtx
, sizeof(*p
));
497 sqlite3_value_free(p
->pVal
);
498 p
->pVal
= sqlite3_value_dup(apArg
[0]);
500 sqlite3_result_error_nomem(pCtx
);
506 static void last_valueInvFunc(
507 sqlite3_context
*pCtx
,
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
));
518 sqlite3_value_free(p
->pVal
);
523 static void last_valueValueFunc(sqlite3_context
*pCtx
){
524 struct LastValueCtx
*p
;
525 p
= (struct LastValueCtx
*)sqlite3_aggregate_context(pCtx
, 0);
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
));
534 sqlite3_result_value(pCtx
, p
->pVal
);
535 sqlite3_value_free(p
->pVal
);
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
569 static void noopStepFunc( /*NO_TEST*/
570 sqlite3_context
*p
, /*NO_TEST*/
572 sqlite3_value
**a
/*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*/
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_FUNC_BUILTIN|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_FUNC_BUILTIN|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
600 #define WINDOWFUNCX(name,nArg,extra) { \
601 nArg, (SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
602 name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
603 noopStepFunc, name ## Name, {0} \
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
){
633 for(p
=pList
; p
; p
=p
->pNextWin
){
634 if( sqlite3StrICmp(p
->zName
, zName
)==0 ) break;
637 sqlite3ErrorMsg(pParse
, "no such window: %s", zName
);
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 referred 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
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(
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
);
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
;
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"
687 if( pFunc
->funcFlags
& SQLITE_FUNC_WINDOW
){
688 sqlite3
*db
= pParse
->db
;
690 sqlite3ErrorMsg(pParse
,
691 "FILTER clause may only be used with aggregate window functions"
694 struct WindowUpdate
{
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
},
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
;
719 if( pWin
->eStart
==TK_FOLLOWING
){
720 pWin
->pStart
= sqlite3Expr(db
, TK_INTEGER
, "1");
727 pWin
->pWFunc
= pFunc
;
731 ** Context object passed through sqlite3WalkExprList() to
732 ** selectWindowRewriteExprCb() by selectWindowRewriteEList().
734 typedef struct WindowRewrite WindowRewrite
;
735 struct WindowRewrite
{
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
;
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. */
760 if( pExpr
->op
!=TK_COLUMN
){
763 int nSrc
= p
->pSrc
->nSrc
;
765 for(i
=0; i
<nSrc
; i
++){
766 if( pExpr
->iTable
==p
->pSrc
->a
[i
].iCursor
) break;
768 if( i
==nSrc
) return WRC_Continue
;
775 if( !ExprHasProperty(pExpr
, EP_WinFunc
) ){
779 for(pWin
=p
->pWin
; pWin
; pWin
=pWin
->pNextWin
){
780 if( pExpr
->y
.pWin
==pWin
){
781 assert( pWin
->pOwner
==pExpr
);
786 /* no break */ deliberate_fall_through
789 case TK_AGG_FUNCTION
:
792 if( pParse
->db
->mallocFailed
) return WRC_Abort
;
795 for(i
=0; i
<p
->pSub
->nExpr
; i
++){
796 if( 0==sqlite3ExprCompare(0, p
->pSub
->a
[i
].pExpr
, pExpr
, -1) ){
803 Expr
*pDup
= sqlite3ExprDup(pParse
->db
, pExpr
, 0);
804 if( pDup
&& pDup
->op
==TK_AGG_FUNCTION
) pDup
->op
= TK_FUNCTION
;
805 p
->pSub
= sqlite3ExprListAppend(pParse
, p
->pSub
, pDup
);
808 int f
= pExpr
->flags
& EP_Collate
;
809 assert( ExprHasProperty(pExpr
, EP_Static
)==0 );
810 ExprSetProperty(pExpr
, EP_Static
);
811 sqlite3ExprDelete(pParse
->db
, pExpr
);
812 ExprClearProperty(pExpr
, EP_Static
);
813 memset(pExpr
, 0, sizeof(Expr
));
815 pExpr
->op
= TK_COLUMN
;
816 pExpr
->iColumn
= (iCol
<0 ? p
->pSub
->nExpr
-1: iCol
);
817 pExpr
->iTable
= p
->pWin
->iEphCsr
;
818 pExpr
->y
.pTab
= p
->pTab
;
821 if( pParse
->db
->mallocFailed
) return WRC_Abort
;
831 static int selectWindowRewriteSelectCb(Walker
*pWalker
, Select
*pSelect
){
832 struct WindowRewrite
*p
= pWalker
->u
.pRewrite
;
833 Select
*pSave
= p
->pSubSelect
;
834 if( pSave
==pSelect
){
837 p
->pSubSelect
= pSelect
;
838 sqlite3WalkSelect(pWalker
, pSelect
);
839 p
->pSubSelect
= pSave
;
846 ** Iterate through each expression in expression-list pEList. For each:
849 ** * aggregate function, or
850 ** * window function with a Window object that is not a member of the
851 ** Window list passed as the second argument (pWin).
853 ** Append the node to output expression-list (*ppSub). And replace it
854 ** with a TK_COLUMN that reads the (N-1)th element of table
855 ** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
856 ** appending the new one.
858 static void selectWindowRewriteEList(
862 ExprList
*pEList
, /* Rewrite expressions in this list */
864 ExprList
**ppSub
/* IN/OUT: Sub-select expression-list */
867 WindowRewrite sRewrite
;
870 memset(&sWalker
, 0, sizeof(Walker
));
871 memset(&sRewrite
, 0, sizeof(WindowRewrite
));
873 sRewrite
.pSub
= *ppSub
;
874 sRewrite
.pWin
= pWin
;
875 sRewrite
.pSrc
= pSrc
;
876 sRewrite
.pTab
= pTab
;
878 sWalker
.pParse
= pParse
;
879 sWalker
.xExprCallback
= selectWindowRewriteExprCb
;
880 sWalker
.xSelectCallback
= selectWindowRewriteSelectCb
;
881 sWalker
.u
.pRewrite
= &sRewrite
;
883 (void)sqlite3WalkExprList(&sWalker
, pEList
);
885 *ppSub
= sRewrite
.pSub
;
889 ** Append a copy of each expression in expression-list pAppend to
890 ** expression list pList. Return a pointer to the result list.
892 static ExprList
*exprListAppendList(
893 Parse
*pParse
, /* Parsing context */
894 ExprList
*pList
, /* List to which to append. Might be NULL */
895 ExprList
*pAppend
, /* List of values to append. Might be NULL */
900 int nInit
= pList
? pList
->nExpr
: 0;
901 for(i
=0; i
<pAppend
->nExpr
; i
++){
902 sqlite3
*db
= pParse
->db
;
903 Expr
*pDup
= sqlite3ExprDup(db
, pAppend
->a
[i
].pExpr
, 0);
904 if( db
->mallocFailed
){
905 sqlite3ExprDelete(db
, pDup
);
911 pSub
= sqlite3ExprSkipCollateAndLikely(pDup
);
912 if( sqlite3ExprIsInteger(pSub
, &iDummy
) ){
914 pSub
->flags
&= ~(EP_IntValue
|EP_IsTrue
|EP_IsFalse
);
918 pList
= sqlite3ExprListAppend(pParse
, pList
, pDup
);
919 if( pList
) pList
->a
[nInit
+i
].fg
.sortFlags
= pAppend
->a
[i
].fg
.sortFlags
;
926 ** When rewriting a query, if the new subquery in the FROM clause
927 ** contains TK_AGG_FUNCTION nodes that refer to an outer query,
928 ** then we have to increase the Expr->op2 values of those nodes
929 ** due to the extra subquery layer that was added.
931 ** See also the incrAggDepth() routine in resolve.c
933 static int sqlite3WindowExtraAggFuncDepth(Walker
*pWalker
, Expr
*pExpr
){
934 if( pExpr
->op
==TK_AGG_FUNCTION
935 && pExpr
->op2
>=pWalker
->walkerDepth
942 static int disallowAggregatesInOrderByCb(Walker
*pWalker
, Expr
*pExpr
){
943 if( pExpr
->op
==TK_AGG_FUNCTION
&& pExpr
->pAggInfo
==0 ){
944 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
945 sqlite3ErrorMsg(pWalker
->pParse
,
946 "misuse of aggregate: %s()", pExpr
->u
.zToken
);
952 ** If the SELECT statement passed as the second argument does not invoke
953 ** any SQL window functions, this function is a no-op. Otherwise, it
954 ** rewrites the SELECT statement so that window function xStep functions
955 ** are invoked in the correct order as described under "SELECT REWRITING"
956 ** at the top of this file.
958 int sqlite3WindowRewrite(Parse
*pParse
, Select
*p
){
962 && ALWAYS((p
->selFlags
& SF_WinRewrite
)==0)
963 && ALWAYS(!IN_RENAME_OBJECT
)
965 Vdbe
*v
= sqlite3GetVdbe(pParse
);
966 sqlite3
*db
= pParse
->db
;
967 Select
*pSub
= 0; /* The subquery */
968 SrcList
*pSrc
= p
->pSrc
;
969 Expr
*pWhere
= p
->pWhere
;
970 ExprList
*pGroupBy
= p
->pGroupBy
;
971 Expr
*pHaving
= p
->pHaving
;
974 ExprList
*pSublist
= 0; /* Expression list for sub-query */
975 Window
*pMWin
= p
->pWin
; /* Main window object */
976 Window
*pWin
; /* Window object iterator */
980 u32 selFlags
= p
->selFlags
;
982 pTab
= sqlite3DbMallocZero(db
, sizeof(Table
));
984 return sqlite3ErrorToParser(db
, SQLITE_NOMEM
);
986 sqlite3AggInfoPersistWalkerInit(&w
, pParse
);
987 sqlite3WalkSelect(&w
, p
);
988 if( (p
->selFlags
& SF_Aggregate
)==0 ){
989 w
.xExprCallback
= disallowAggregatesInOrderByCb
;
990 w
.xSelectCallback
= 0;
991 sqlite3WalkExprList(&w
, p
->pOrderBy
);
998 p
->selFlags
&= ~SF_Aggregate
;
999 p
->selFlags
|= SF_WinRewrite
;
1001 /* Create the ORDER BY clause for the sub-select. This is the concatenation
1002 ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
1003 ** redundant, remove the ORDER BY from the parent SELECT. */
1004 pSort
= exprListAppendList(pParse
, 0, pMWin
->pPartition
, 1);
1005 pSort
= exprListAppendList(pParse
, pSort
, pMWin
->pOrderBy
, 1);
1006 if( pSort
&& p
->pOrderBy
&& p
->pOrderBy
->nExpr
<=pSort
->nExpr
){
1007 int nSave
= pSort
->nExpr
;
1008 pSort
->nExpr
= p
->pOrderBy
->nExpr
;
1009 if( sqlite3ExprListCompare(pSort
, p
->pOrderBy
, -1)==0 ){
1010 sqlite3ExprListDelete(db
, p
->pOrderBy
);
1013 pSort
->nExpr
= nSave
;
1016 /* Assign a cursor number for the ephemeral table used to buffer rows.
1017 ** The OpenEphemeral instruction is coded later, after it is known how
1018 ** many columns the table will have. */
1019 pMWin
->iEphCsr
= pParse
->nTab
++;
1022 selectWindowRewriteEList(pParse
, pMWin
, pSrc
, p
->pEList
, pTab
, &pSublist
);
1023 selectWindowRewriteEList(pParse
, pMWin
, pSrc
, p
->pOrderBy
, pTab
, &pSublist
);
1024 pMWin
->nBufferCol
= (pSublist
? pSublist
->nExpr
: 0);
1026 /* Append the PARTITION BY and ORDER BY expressions to the to the
1027 ** sub-select expression list. They are required to figure out where
1028 ** boundaries for partitions and sets of peer rows lie. */
1029 pSublist
= exprListAppendList(pParse
, pSublist
, pMWin
->pPartition
, 0);
1030 pSublist
= exprListAppendList(pParse
, pSublist
, pMWin
->pOrderBy
, 0);
1032 /* Append the arguments passed to each window function to the
1033 ** sub-select expression list. Also allocate two registers for each
1034 ** window function - one for the accumulator, another for interim
1036 for(pWin
=pMWin
; pWin
; pWin
=pWin
->pNextWin
){
1038 assert( ExprUseXList(pWin
->pOwner
) );
1039 assert( pWin
->pWFunc
!=0 );
1040 pArgs
= pWin
->pOwner
->x
.pList
;
1041 if( pWin
->pWFunc
->funcFlags
& SQLITE_SUBTYPE
){
1042 selectWindowRewriteEList(pParse
, pMWin
, pSrc
, pArgs
, pTab
, &pSublist
);
1043 pWin
->iArgCol
= (pSublist
? pSublist
->nExpr
: 0);
1044 pWin
->bExprArgs
= 1;
1046 pWin
->iArgCol
= (pSublist
? pSublist
->nExpr
: 0);
1047 pSublist
= exprListAppendList(pParse
, pSublist
, pArgs
, 0);
1049 if( pWin
->pFilter
){
1050 Expr
*pFilter
= sqlite3ExprDup(db
, pWin
->pFilter
, 0);
1051 pSublist
= sqlite3ExprListAppend(pParse
, pSublist
, pFilter
);
1053 pWin
->regAccum
= ++pParse
->nMem
;
1054 pWin
->regResult
= ++pParse
->nMem
;
1055 sqlite3VdbeAddOp2(v
, OP_Null
, 0, pWin
->regAccum
);
1058 /* If there is no ORDER BY or PARTITION BY clause, and the window
1059 ** function accepts zero arguments, and there are no other columns
1060 ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
1061 ** that pSublist is still NULL here. Add a constant expression here to
1062 ** keep everything legal in this case.
1065 pSublist
= sqlite3ExprListAppend(pParse
, 0,
1066 sqlite3Expr(db
, TK_INTEGER
, "0")
1070 pSub
= sqlite3SelectNew(
1071 pParse
, pSublist
, pSrc
, pWhere
, pGroupBy
, pHaving
, pSort
, 0, 0
1073 TREETRACE(0x40,pParse
,pSub
,
1074 ("New window-function subquery in FROM clause of (%u/%p)\n",
1076 p
->pSrc
= sqlite3SrcListAppend(pParse
, 0, 0, 0);
1077 assert( pSub
!=0 || p
->pSrc
==0 ); /* Due to db->mallocFailed test inside
1078 ** of sqlite3DbMallocRawNN() called from
1079 ** sqlite3SrcListAppend() */
1082 p
->pSrc
->a
[0].pSelect
= pSub
;
1083 p
->pSrc
->a
[0].fg
.isCorrelated
= 1;
1084 sqlite3SrcListAssignCursors(pParse
, p
->pSrc
);
1085 pSub
->selFlags
|= SF_Expanded
|SF_OrderByReqd
;
1086 pTab2
= sqlite3ResultSetOfSelect(pParse
, pSub
, SQLITE_AFF_NONE
);
1087 pSub
->selFlags
|= (selFlags
& SF_Aggregate
);
1089 /* Might actually be some other kind of error, but in that case
1090 ** pParse->nErr will be set, so if SQLITE_NOMEM is set, we will get
1091 ** the correct error message regardless. */
1094 memcpy(pTab
, pTab2
, sizeof(Table
));
1095 pTab
->tabFlags
|= TF_Ephemeral
;
1096 p
->pSrc
->a
[0].pTab
= pTab
;
1098 memset(&w
, 0, sizeof(w
));
1099 w
.xExprCallback
= sqlite3WindowExtraAggFuncDepth
;
1100 w
.xSelectCallback
= sqlite3WalkerDepthIncrease
;
1101 w
.xSelectCallback2
= sqlite3WalkerDepthDecrease
;
1102 sqlite3WalkSelect(&w
, pSub
);
1105 sqlite3SelectDelete(db
, pSub
);
1107 if( db
->mallocFailed
) rc
= SQLITE_NOMEM
;
1109 /* Defer deleting the temporary table pTab because if an error occurred,
1110 ** there could still be references to that table embedded in the
1111 ** result-set or ORDER BY clause of the SELECT statement p. */
1112 sqlite3ParserAddCleanup(pParse
, sqlite3DbFree
, pTab
);
1115 assert( rc
==SQLITE_OK
|| pParse
->nErr
!=0 );
1120 ** Unlink the Window object from the Select to which it is attached,
1121 ** if it is attached.
1123 void sqlite3WindowUnlinkFromSelect(Window
*p
){
1125 *p
->ppThis
= p
->pNextWin
;
1126 if( p
->pNextWin
) p
->pNextWin
->ppThis
= p
->ppThis
;
1132 ** Free the Window object passed as the second argument.
1134 void sqlite3WindowDelete(sqlite3
*db
, Window
*p
){
1136 sqlite3WindowUnlinkFromSelect(p
);
1137 sqlite3ExprDelete(db
, p
->pFilter
);
1138 sqlite3ExprListDelete(db
, p
->pPartition
);
1139 sqlite3ExprListDelete(db
, p
->pOrderBy
);
1140 sqlite3ExprDelete(db
, p
->pEnd
);
1141 sqlite3ExprDelete(db
, p
->pStart
);
1142 sqlite3DbFree(db
, p
->zName
);
1143 sqlite3DbFree(db
, p
->zBase
);
1144 sqlite3DbFree(db
, p
);
1149 ** Free the linked list of Window objects starting at the second argument.
1151 void sqlite3WindowListDelete(sqlite3
*db
, Window
*p
){
1153 Window
*pNext
= p
->pNextWin
;
1154 sqlite3WindowDelete(db
, p
);
1160 ** The argument expression is an PRECEDING or FOLLOWING offset. The
1161 ** value should be a non-negative integer. If the value is not a
1162 ** constant, change it to NULL. The fact that it is then a non-negative
1163 ** integer will be caught later. But it is important not to leave
1164 ** variable values in the expression tree.
1166 static Expr
*sqlite3WindowOffsetExpr(Parse
*pParse
, Expr
*pExpr
){
1167 if( 0==sqlite3ExprIsConstant(pExpr
) ){
1168 if( IN_RENAME_OBJECT
) sqlite3RenameExprUnmap(pParse
, pExpr
);
1169 sqlite3ExprDelete(pParse
->db
, pExpr
);
1170 pExpr
= sqlite3ExprAlloc(pParse
->db
, TK_NULL
, 0, 0);
1176 ** Allocate and return a new Window object describing a Window Definition.
1178 Window
*sqlite3WindowAlloc(
1179 Parse
*pParse
, /* Parsing context */
1180 int eType
, /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */
1181 int eStart
, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
1182 Expr
*pStart
, /* Start window size if TK_PRECEDING or FOLLOWING */
1183 int eEnd
, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
1184 Expr
*pEnd
, /* End window size if TK_FOLLOWING or PRECEDING */
1185 u8 eExclude
/* EXCLUDE clause */
1188 int bImplicitFrame
= 0;
1190 /* Parser assures the following: */
1191 assert( eType
==0 || eType
==TK_RANGE
|| eType
==TK_ROWS
|| eType
==TK_GROUPS
);
1192 assert( eStart
==TK_CURRENT
|| eStart
==TK_PRECEDING
1193 || eStart
==TK_UNBOUNDED
|| eStart
==TK_FOLLOWING
);
1194 assert( eEnd
==TK_CURRENT
|| eEnd
==TK_FOLLOWING
1195 || eEnd
==TK_UNBOUNDED
|| eEnd
==TK_PRECEDING
);
1196 assert( (eStart
==TK_PRECEDING
|| eStart
==TK_FOLLOWING
)==(pStart
!=0) );
1197 assert( (eEnd
==TK_FOLLOWING
|| eEnd
==TK_PRECEDING
)==(pEnd
!=0) );
1204 /* Additionally, the
1205 ** starting boundary type may not occur earlier in the following list than
1206 ** the ending boundary type:
1208 ** UNBOUNDED PRECEDING
1212 ** UNBOUNDED FOLLOWING
1214 ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
1215 ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
1218 if( (eStart
==TK_CURRENT
&& eEnd
==TK_PRECEDING
)
1219 || (eStart
==TK_FOLLOWING
&& (eEnd
==TK_PRECEDING
|| eEnd
==TK_CURRENT
))
1221 sqlite3ErrorMsg(pParse
, "unsupported frame specification");
1222 goto windowAllocErr
;
1225 pWin
= (Window
*)sqlite3DbMallocZero(pParse
->db
, sizeof(Window
));
1226 if( pWin
==0 ) goto windowAllocErr
;
1227 pWin
->eFrmType
= eType
;
1228 pWin
->eStart
= eStart
;
1230 if( eExclude
==0 && OptimizationDisabled(pParse
->db
, SQLITE_WindowFunc
) ){
1233 pWin
->eExclude
= eExclude
;
1234 pWin
->bImplicitFrame
= bImplicitFrame
;
1235 pWin
->pEnd
= sqlite3WindowOffsetExpr(pParse
, pEnd
);
1236 pWin
->pStart
= sqlite3WindowOffsetExpr(pParse
, pStart
);
1240 sqlite3ExprDelete(pParse
->db
, pEnd
);
1241 sqlite3ExprDelete(pParse
->db
, pStart
);
1246 ** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
1247 ** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
1248 ** equivalent nul-terminated string.
1250 Window
*sqlite3WindowAssemble(
1253 ExprList
*pPartition
,
1258 pWin
->pPartition
= pPartition
;
1259 pWin
->pOrderBy
= pOrderBy
;
1261 pWin
->zBase
= sqlite3DbStrNDup(pParse
->db
, pBase
->z
, pBase
->n
);
1264 sqlite3ExprListDelete(pParse
->db
, pPartition
);
1265 sqlite3ExprListDelete(pParse
->db
, pOrderBy
);
1271 ** Window *pWin has just been created from a WINDOW clause. Token pBase
1272 ** is the base window. Earlier windows from the same WINDOW clause are
1273 ** stored in the linked list starting at pWin->pNextWin. This function
1274 ** either updates *pWin according to the base specification, or else
1275 ** leaves an error in pParse.
1277 void sqlite3WindowChain(Parse
*pParse
, Window
*pWin
, Window
*pList
){
1279 sqlite3
*db
= pParse
->db
;
1280 Window
*pExist
= windowFind(pParse
, pList
, pWin
->zBase
);
1282 const char *zErr
= 0;
1283 /* Check for errors */
1284 if( pWin
->pPartition
){
1285 zErr
= "PARTITION clause";
1286 }else if( pExist
->pOrderBy
&& pWin
->pOrderBy
){
1287 zErr
= "ORDER BY clause";
1288 }else if( pExist
->bImplicitFrame
==0 ){
1289 zErr
= "frame specification";
1292 sqlite3ErrorMsg(pParse
,
1293 "cannot override %s of window: %s", zErr
, pWin
->zBase
1296 pWin
->pPartition
= sqlite3ExprListDup(db
, pExist
->pPartition
, 0);
1297 if( pExist
->pOrderBy
){
1298 assert( pWin
->pOrderBy
==0 );
1299 pWin
->pOrderBy
= sqlite3ExprListDup(db
, pExist
->pOrderBy
, 0);
1301 sqlite3DbFree(db
, pWin
->zBase
);
1309 ** Attach window object pWin to expression p.
1311 void sqlite3WindowAttach(Parse
*pParse
, Expr
*p
, Window
*pWin
){
1313 assert( p
->op
==TK_FUNCTION
);
1315 assert( ExprIsFullSize(p
) );
1317 ExprSetProperty(p
, EP_WinFunc
|EP_FullSize
);
1319 if( (p
->flags
& EP_Distinct
) && pWin
->eFrmType
!=TK_FILTER
){
1320 sqlite3ErrorMsg(pParse
,
1321 "DISTINCT is not supported for window functions"
1325 sqlite3WindowDelete(pParse
->db
, pWin
);
1330 ** Possibly link window pWin into the list at pSel->pWin (window functions
1331 ** to be processed as part of SELECT statement pSel). The window is linked
1332 ** in if either (a) there are no other windows already linked to this
1333 ** SELECT, or (b) the windows already linked use a compatible window frame.
1335 void sqlite3WindowLink(Select
*pSel
, Window
*pWin
){
1337 if( 0==pSel
->pWin
|| 0==sqlite3WindowCompare(0, pSel
->pWin
, pWin
, 0) ){
1338 pWin
->pNextWin
= pSel
->pWin
;
1340 pSel
->pWin
->ppThis
= &pWin
->pNextWin
;
1343 pWin
->ppThis
= &pSel
->pWin
;
1345 if( sqlite3ExprListCompare(pWin
->pPartition
, pSel
->pWin
->pPartition
,-1) ){
1346 pSel
->selFlags
|= SF_MultiPart
;
1353 ** Return 0 if the two window objects are identical, 1 if they are
1354 ** different, or 2 if it cannot be determined if the objects are identical
1355 ** or not. Identical window objects can be processed in a single scan.
1357 int sqlite3WindowCompare(
1358 const Parse
*pParse
,
1364 if( NEVER(p1
==0) || NEVER(p2
==0) ) return 1;
1365 if( p1
->eFrmType
!=p2
->eFrmType
) return 1;
1366 if( p1
->eStart
!=p2
->eStart
) return 1;
1367 if( p1
->eEnd
!=p2
->eEnd
) return 1;
1368 if( p1
->eExclude
!=p2
->eExclude
) return 1;
1369 if( sqlite3ExprCompare(pParse
, p1
->pStart
, p2
->pStart
, -1) ) return 1;
1370 if( sqlite3ExprCompare(pParse
, p1
->pEnd
, p2
->pEnd
, -1) ) return 1;
1371 if( (res
= sqlite3ExprListCompare(p1
->pPartition
, p2
->pPartition
, -1)) ){
1374 if( (res
= sqlite3ExprListCompare(p1
->pOrderBy
, p2
->pOrderBy
, -1)) ){
1378 if( (res
= sqlite3ExprCompare(pParse
, p1
->pFilter
, p2
->pFilter
, -1)) ){
1387 ** This is called by code in select.c before it calls sqlite3WhereBegin()
1388 ** to begin iterating through the sub-query results. It is used to allocate
1389 ** and initialize registers and cursors used by sqlite3WindowCodeStep().
1391 void sqlite3WindowCodeInit(Parse
*pParse
, Select
*pSelect
){
1392 int nEphExpr
= pSelect
->pSrc
->a
[0].pSelect
->pEList
->nExpr
;
1393 Window
*pMWin
= pSelect
->pWin
;
1395 Vdbe
*v
= sqlite3GetVdbe(pParse
);
1397 sqlite3VdbeAddOp2(v
, OP_OpenEphemeral
, pMWin
->iEphCsr
, nEphExpr
);
1398 sqlite3VdbeAddOp2(v
, OP_OpenDup
, pMWin
->iEphCsr
+1, pMWin
->iEphCsr
);
1399 sqlite3VdbeAddOp2(v
, OP_OpenDup
, pMWin
->iEphCsr
+2, pMWin
->iEphCsr
);
1400 sqlite3VdbeAddOp2(v
, OP_OpenDup
, pMWin
->iEphCsr
+3, pMWin
->iEphCsr
);
1402 /* Allocate registers to use for PARTITION BY values, if any. Initialize
1403 ** said registers to NULL. */
1404 if( pMWin
->pPartition
){
1405 int nExpr
= pMWin
->pPartition
->nExpr
;
1406 pMWin
->regPart
= pParse
->nMem
+1;
1407 pParse
->nMem
+= nExpr
;
1408 sqlite3VdbeAddOp3(v
, OP_Null
, 0, pMWin
->regPart
, pMWin
->regPart
+nExpr
-1);
1411 pMWin
->regOne
= ++pParse
->nMem
;
1412 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, pMWin
->regOne
);
1414 if( pMWin
->eExclude
){
1415 pMWin
->regStartRowid
= ++pParse
->nMem
;
1416 pMWin
->regEndRowid
= ++pParse
->nMem
;
1417 pMWin
->csrApp
= pParse
->nTab
++;
1418 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, pMWin
->regStartRowid
);
1419 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, pMWin
->regEndRowid
);
1420 sqlite3VdbeAddOp2(v
, OP_OpenDup
, pMWin
->csrApp
, pMWin
->iEphCsr
);
1424 for(pWin
=pMWin
; pWin
; pWin
=pWin
->pNextWin
){
1425 FuncDef
*p
= pWin
->pWFunc
;
1426 if( (p
->funcFlags
& SQLITE_FUNC_MINMAX
) && pWin
->eStart
!=TK_UNBOUNDED
){
1427 /* The inline versions of min() and max() require a single ephemeral
1428 ** table and 3 registers. The registers are used as follows:
1430 ** regApp+0: slot to copy min()/max() argument to for MakeRecord
1431 ** regApp+1: integer value used to ensure keys are unique
1432 ** regApp+2: output of MakeRecord
1436 assert( ExprUseXList(pWin
->pOwner
) );
1437 pList
= pWin
->pOwner
->x
.pList
;
1438 pKeyInfo
= sqlite3KeyInfoFromExprList(pParse
, pList
, 0, 0);
1439 pWin
->csrApp
= pParse
->nTab
++;
1440 pWin
->regApp
= pParse
->nMem
+1;
1442 if( pKeyInfo
&& pWin
->pWFunc
->zName
[1]=='i' ){
1443 assert( pKeyInfo
->aSortFlags
[0]==0 );
1444 pKeyInfo
->aSortFlags
[0] = KEYINFO_ORDER_DESC
;
1446 sqlite3VdbeAddOp2(v
, OP_OpenEphemeral
, pWin
->csrApp
, 2);
1447 sqlite3VdbeAppendP4(v
, pKeyInfo
, P4_KEYINFO
);
1448 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, pWin
->regApp
+1);
1450 else if( p
->zName
==nth_valueName
|| p
->zName
==first_valueName
){
1451 /* Allocate two registers at pWin->regApp. These will be used to
1452 ** store the start and end index of the current frame. */
1453 pWin
->regApp
= pParse
->nMem
+1;
1454 pWin
->csrApp
= pParse
->nTab
++;
1456 sqlite3VdbeAddOp2(v
, OP_OpenDup
, pWin
->csrApp
, pMWin
->iEphCsr
);
1458 else if( p
->zName
==leadName
|| p
->zName
==lagName
){
1459 pWin
->csrApp
= pParse
->nTab
++;
1460 sqlite3VdbeAddOp2(v
, OP_OpenDup
, pWin
->csrApp
, pMWin
->iEphCsr
);
1465 #define WINDOW_STARTING_INT 0
1466 #define WINDOW_ENDING_INT 1
1467 #define WINDOW_NTH_VALUE_INT 2
1468 #define WINDOW_STARTING_NUM 3
1469 #define WINDOW_ENDING_NUM 4
1472 ** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
1473 ** value of the second argument to nth_value() (eCond==2) has just been
1474 ** evaluated and the result left in register reg. This function generates VM
1475 ** code to check that the value is a non-negative integer and throws an
1476 ** exception if it is not.
1478 static void windowCheckValue(Parse
*pParse
, int reg
, int eCond
){
1479 static const char *azErr
[] = {
1480 "frame starting offset must be a non-negative integer",
1481 "frame ending offset must be a non-negative integer",
1482 "second argument to nth_value must be a positive integer",
1483 "frame starting offset must be a non-negative number",
1484 "frame ending offset must be a non-negative number",
1486 static int aOp
[] = { OP_Ge
, OP_Ge
, OP_Gt
, OP_Ge
, OP_Ge
};
1487 Vdbe
*v
= sqlite3GetVdbe(pParse
);
1488 int regZero
= sqlite3GetTempReg(pParse
);
1489 assert( eCond
>=0 && eCond
<ArraySize(azErr
) );
1490 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, regZero
);
1491 if( eCond
>=WINDOW_STARTING_NUM
){
1492 int regString
= sqlite3GetTempReg(pParse
);
1493 sqlite3VdbeAddOp4(v
, OP_String8
, 0, regString
, 0, "", P4_STATIC
);
1494 sqlite3VdbeAddOp3(v
, OP_Ge
, regString
, sqlite3VdbeCurrentAddr(v
)+2, reg
);
1495 sqlite3VdbeChangeP5(v
, SQLITE_AFF_NUMERIC
|SQLITE_JUMPIFNULL
);
1497 assert( eCond
==3 || eCond
==4 );
1498 VdbeCoverageIf(v
, eCond
==3);
1499 VdbeCoverageIf(v
, eCond
==4);
1501 sqlite3VdbeAddOp2(v
, OP_MustBeInt
, reg
, sqlite3VdbeCurrentAddr(v
)+2);
1503 assert( eCond
==0 || eCond
==1 || eCond
==2 );
1504 VdbeCoverageIf(v
, eCond
==0);
1505 VdbeCoverageIf(v
, eCond
==1);
1506 VdbeCoverageIf(v
, eCond
==2);
1508 sqlite3VdbeAddOp3(v
, aOp
[eCond
], regZero
, sqlite3VdbeCurrentAddr(v
)+2, reg
);
1509 sqlite3VdbeChangeP5(v
, SQLITE_AFF_NUMERIC
);
1510 VdbeCoverageNeverNullIf(v
, eCond
==0); /* NULL case captured by */
1511 VdbeCoverageNeverNullIf(v
, eCond
==1); /* the OP_MustBeInt */
1512 VdbeCoverageNeverNullIf(v
, eCond
==2);
1513 VdbeCoverageNeverNullIf(v
, eCond
==3); /* NULL case caught by */
1514 VdbeCoverageNeverNullIf(v
, eCond
==4); /* the OP_Ge */
1515 sqlite3MayAbort(pParse
);
1516 sqlite3VdbeAddOp2(v
, OP_Halt
, SQLITE_ERROR
, OE_Abort
);
1517 sqlite3VdbeAppendP4(v
, (void*)azErr
[eCond
], P4_STATIC
);
1518 sqlite3ReleaseTempReg(pParse
, regZero
);
1522 ** Return the number of arguments passed to the window-function associated
1523 ** with the object passed as the only argument to this function.
1525 static int windowArgCount(Window
*pWin
){
1526 const ExprList
*pList
;
1527 assert( ExprUseXList(pWin
->pOwner
) );
1528 pList
= pWin
->pOwner
->x
.pList
;
1529 return (pList
? pList
->nExpr
: 0);
1532 typedef struct WindowCodeArg WindowCodeArg
;
1533 typedef struct WindowCsrAndReg WindowCsrAndReg
;
1536 ** See comments above struct WindowCodeArg.
1538 struct WindowCsrAndReg
{
1539 int csr
; /* Cursor number */
1540 int reg
; /* First in array of peer values */
1544 ** A single instance of this structure is allocated on the stack by
1545 ** sqlite3WindowCodeStep() and a pointer to it passed to the various helper
1546 ** routines. This is to reduce the number of arguments required by each
1550 ** Each window function requires an accumulator register (just as an
1551 ** ordinary aggregate function does). This variable is set to the first
1552 ** in an array of accumulator registers - one for each window function
1553 ** in the WindowCodeArg.pMWin list.
1556 ** The window functions implementation sometimes caches the input rows
1557 ** that it processes in a temporary table. If it is not zero, this
1558 ** variable indicates when rows may be removed from the temp table (in
1559 ** order to reduce memory requirements - it would always be safe just
1560 ** to leave them there). Possible values for eDelete are:
1562 ** WINDOW_RETURN_ROW:
1563 ** An input row can be discarded after it is returned to the caller.
1565 ** WINDOW_AGGINVERSE:
1566 ** An input row can be discarded after the window functions xInverse()
1567 ** callbacks have been invoked in it.
1570 ** An input row can be discarded after the window functions xStep()
1571 ** callbacks have been invoked in it.
1573 ** start,current,end
1574 ** Consider a window-frame similar to the following:
1576 ** (ORDER BY a, b GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING)
1578 ** The windows functions implementation caches the input rows in a temp
1579 ** table, sorted by "a, b" (it actually populates the cache lazily, and
1580 ** aggressively removes rows once they are no longer required, but that's
1581 ** a mere detail). It keeps three cursors open on the temp table. One
1582 ** (current) that points to the next row to return to the query engine
1583 ** once its window function values have been calculated. Another (end)
1584 ** points to the next row to call the xStep() method of each window function
1585 ** on (so that it is 2 groups ahead of current). And a third (start) that
1586 ** points to the next row to call the xInverse() method of each window
1589 ** Each cursor (start, current and end) consists of a VDBE cursor
1590 ** (WindowCsrAndReg.csr) and an array of registers (starting at
1591 ** WindowCodeArg.reg) that always contains a copy of the peer values
1592 ** read from the corresponding cursor.
1594 ** Depending on the window-frame in question, all three cursors may not
1595 ** be required. In this case both WindowCodeArg.csr and reg are set to
1598 struct WindowCodeArg
{
1599 Parse
*pParse
; /* Parse context */
1600 Window
*pMWin
; /* First in list of functions being processed */
1601 Vdbe
*pVdbe
; /* VDBE object */
1602 int addrGosub
; /* OP_Gosub to this address to return one row */
1603 int regGosub
; /* Register used with OP_Gosub(addrGosub) */
1604 int regArg
; /* First in array of accumulator registers */
1605 int eDelete
; /* See above */
1608 WindowCsrAndReg start
;
1609 WindowCsrAndReg current
;
1610 WindowCsrAndReg end
;
1614 ** Generate VM code to read the window frames peer values from cursor csr into
1615 ** an array of registers starting at reg.
1617 static void windowReadPeerValues(
1622 Window
*pMWin
= p
->pMWin
;
1623 ExprList
*pOrderBy
= pMWin
->pOrderBy
;
1625 Vdbe
*v
= sqlite3GetVdbe(p
->pParse
);
1626 ExprList
*pPart
= pMWin
->pPartition
;
1627 int iColOff
= pMWin
->nBufferCol
+ (pPart
? pPart
->nExpr
: 0);
1629 for(i
=0; i
<pOrderBy
->nExpr
; i
++){
1630 sqlite3VdbeAddOp3(v
, OP_Column
, csr
, iColOff
+i
, reg
+i
);
1636 ** Generate VM code to invoke either xStep() (if bInverse is 0) or
1637 ** xInverse (if bInverse is non-zero) for each window function in the
1638 ** linked list starting at pMWin. Or, for built-in window functions
1639 ** that do not use the standard function API, generate the required
1642 ** If argument csr is greater than or equal to 0, then argument reg is
1643 ** the first register in an array of registers guaranteed to be large
1644 ** enough to hold the array of arguments for each function. In this case
1645 ** the arguments are extracted from the current row of csr into the
1646 ** array of registers before invoking OP_AggStep or OP_AggInverse
1648 ** Or, if csr is less than zero, then the array of registers at reg is
1649 ** already populated with all columns from the current row of the sub-query.
1651 ** If argument regPartSize is non-zero, then it is a register containing the
1652 ** number of rows in the current partition.
1654 static void windowAggStep(
1656 Window
*pMWin
, /* Linked list of window functions */
1657 int csr
, /* Read arguments from this cursor */
1658 int bInverse
, /* True to invoke xInverse instead of xStep */
1659 int reg
/* Array of registers */
1661 Parse
*pParse
= p
->pParse
;
1662 Vdbe
*v
= sqlite3GetVdbe(pParse
);
1664 for(pWin
=pMWin
; pWin
; pWin
=pWin
->pNextWin
){
1665 FuncDef
*pFunc
= pWin
->pWFunc
;
1667 int nArg
= pWin
->bExprArgs
? 0 : windowArgCount(pWin
);
1670 assert( bInverse
==0 || pWin
->eStart
!=TK_UNBOUNDED
);
1672 /* All OVER clauses in the same window function aggregate step must
1674 assert( pWin
==pMWin
|| sqlite3WindowCompare(pParse
,pWin
,pMWin
,0)!=1 );
1676 for(i
=0; i
<nArg
; i
++){
1677 if( i
!=1 || pFunc
->zName
!=nth_valueName
){
1678 sqlite3VdbeAddOp3(v
, OP_Column
, csr
, pWin
->iArgCol
+i
, reg
+i
);
1680 sqlite3VdbeAddOp3(v
, OP_Column
, pMWin
->iEphCsr
, pWin
->iArgCol
+i
, reg
+i
);
1685 if( pMWin
->regStartRowid
==0
1686 && (pFunc
->funcFlags
& SQLITE_FUNC_MINMAX
)
1687 && (pWin
->eStart
!=TK_UNBOUNDED
)
1689 int addrIsNull
= sqlite3VdbeAddOp1(v
, OP_IsNull
, regArg
);
1692 sqlite3VdbeAddOp2(v
, OP_AddImm
, pWin
->regApp
+1, 1);
1693 sqlite3VdbeAddOp2(v
, OP_SCopy
, regArg
, pWin
->regApp
);
1694 sqlite3VdbeAddOp3(v
, OP_MakeRecord
, pWin
->regApp
, 2, pWin
->regApp
+2);
1695 sqlite3VdbeAddOp2(v
, OP_IdxInsert
, pWin
->csrApp
, pWin
->regApp
+2);
1697 sqlite3VdbeAddOp4Int(v
, OP_SeekGE
, pWin
->csrApp
, 0, regArg
, 1);
1698 VdbeCoverageNeverTaken(v
);
1699 sqlite3VdbeAddOp1(v
, OP_Delete
, pWin
->csrApp
);
1700 sqlite3VdbeJumpHere(v
, sqlite3VdbeCurrentAddr(v
)-2);
1702 sqlite3VdbeJumpHere(v
, addrIsNull
);
1703 }else if( pWin
->regApp
){
1704 assert( pFunc
->zName
==nth_valueName
1705 || pFunc
->zName
==first_valueName
1707 assert( bInverse
==0 || bInverse
==1 );
1708 sqlite3VdbeAddOp2(v
, OP_AddImm
, pWin
->regApp
+1-bInverse
, 1);
1709 }else if( pFunc
->xSFunc
!=noopStepFunc
){
1711 if( pWin
->pFilter
){
1713 assert( ExprUseXList(pWin
->pOwner
) );
1714 assert( pWin
->bExprArgs
|| !nArg
||nArg
==pWin
->pOwner
->x
.pList
->nExpr
);
1715 assert( pWin
->bExprArgs
|| nArg
||pWin
->pOwner
->x
.pList
==0 );
1716 regTmp
= sqlite3GetTempReg(pParse
);
1717 sqlite3VdbeAddOp3(v
, OP_Column
, csr
, pWin
->iArgCol
+nArg
,regTmp
);
1718 addrIf
= sqlite3VdbeAddOp3(v
, OP_IfNot
, regTmp
, 0, 1);
1720 sqlite3ReleaseTempReg(pParse
, regTmp
);
1723 if( pWin
->bExprArgs
){
1724 int iOp
= sqlite3VdbeCurrentAddr(v
);
1727 assert( ExprUseXList(pWin
->pOwner
) );
1728 nArg
= pWin
->pOwner
->x
.pList
->nExpr
;
1729 regArg
= sqlite3GetTempRange(pParse
, nArg
);
1730 sqlite3ExprCodeExprList(pParse
, pWin
->pOwner
->x
.pList
, regArg
, 0, 0);
1732 for(iEnd
=sqlite3VdbeCurrentAddr(v
); iOp
<iEnd
; iOp
++){
1733 VdbeOp
*pOp
= sqlite3VdbeGetOp(v
, iOp
);
1734 if( pOp
->opcode
==OP_Column
&& pOp
->p1
==pMWin
->iEphCsr
){
1739 if( pFunc
->funcFlags
& SQLITE_FUNC_NEEDCOLL
){
1742 assert( ExprUseXList(pWin
->pOwner
) );
1743 pColl
= sqlite3ExprNNCollSeq(pParse
, pWin
->pOwner
->x
.pList
->a
[0].pExpr
);
1744 sqlite3VdbeAddOp4(v
, OP_CollSeq
, 0,0,0, (const char*)pColl
, P4_COLLSEQ
);
1746 sqlite3VdbeAddOp3(v
, bInverse
? OP_AggInverse
: OP_AggStep
,
1747 bInverse
, regArg
, pWin
->regAccum
);
1748 sqlite3VdbeAppendP4(v
, pFunc
, P4_FUNCDEF
);
1749 sqlite3VdbeChangeP5(v
, (u8
)nArg
);
1750 if( pWin
->bExprArgs
){
1751 sqlite3ReleaseTempRange(pParse
, regArg
, nArg
);
1753 if( addrIf
) sqlite3VdbeJumpHere(v
, addrIf
);
1759 ** Values that may be passed as the second argument to windowCodeOp().
1761 #define WINDOW_RETURN_ROW 1
1762 #define WINDOW_AGGINVERSE 2
1763 #define WINDOW_AGGSTEP 3
1766 ** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
1767 ** (bFin==1) for each window function in the linked list starting at
1768 ** pMWin. Or, for built-in window-functions that do not use the standard
1769 ** API, generate the equivalent VM code.
1771 static void windowAggFinal(WindowCodeArg
*p
, int bFin
){
1772 Parse
*pParse
= p
->pParse
;
1773 Window
*pMWin
= p
->pMWin
;
1774 Vdbe
*v
= sqlite3GetVdbe(pParse
);
1777 for(pWin
=pMWin
; pWin
; pWin
=pWin
->pNextWin
){
1778 if( pMWin
->regStartRowid
==0
1779 && (pWin
->pWFunc
->funcFlags
& SQLITE_FUNC_MINMAX
)
1780 && (pWin
->eStart
!=TK_UNBOUNDED
)
1782 sqlite3VdbeAddOp2(v
, OP_Null
, 0, pWin
->regResult
);
1783 sqlite3VdbeAddOp1(v
, OP_Last
, pWin
->csrApp
);
1785 sqlite3VdbeAddOp3(v
, OP_Column
, pWin
->csrApp
, 0, pWin
->regResult
);
1786 sqlite3VdbeJumpHere(v
, sqlite3VdbeCurrentAddr(v
)-2);
1787 }else if( pWin
->regApp
){
1788 assert( pMWin
->regStartRowid
==0 );
1790 int nArg
= windowArgCount(pWin
);
1792 sqlite3VdbeAddOp2(v
, OP_AggFinal
, pWin
->regAccum
, nArg
);
1793 sqlite3VdbeAppendP4(v
, pWin
->pWFunc
, P4_FUNCDEF
);
1794 sqlite3VdbeAddOp2(v
, OP_Copy
, pWin
->regAccum
, pWin
->regResult
);
1795 sqlite3VdbeAddOp2(v
, OP_Null
, 0, pWin
->regAccum
);
1797 sqlite3VdbeAddOp3(v
, OP_AggValue
,pWin
->regAccum
,nArg
,pWin
->regResult
);
1798 sqlite3VdbeAppendP4(v
, pWin
->pWFunc
, P4_FUNCDEF
);
1805 ** Generate code to calculate the current values of all window functions in the
1806 ** p->pMWin list by doing a full scan of the current window frame. Store the
1807 ** results in the Window.regResult registers, ready to return the upper
1810 static void windowFullScan(WindowCodeArg
*p
){
1812 Parse
*pParse
= p
->pParse
;
1813 Window
*pMWin
= p
->pMWin
;
1816 int regCRowid
= 0; /* Current rowid value */
1817 int regCPeer
= 0; /* Current peer values */
1818 int regRowid
= 0; /* AggStep rowid value */
1819 int regPeer
= 0; /* AggStep peer values */
1827 VdbeModuleComment((v
, "windowFullScan begin"));
1830 csr
= pMWin
->csrApp
;
1831 nPeer
= (pMWin
->pOrderBy
? pMWin
->pOrderBy
->nExpr
: 0);
1833 lblNext
= sqlite3VdbeMakeLabel(pParse
);
1834 lblBrk
= sqlite3VdbeMakeLabel(pParse
);
1836 regCRowid
= sqlite3GetTempReg(pParse
);
1837 regRowid
= sqlite3GetTempReg(pParse
);
1839 regCPeer
= sqlite3GetTempRange(pParse
, nPeer
);
1840 regPeer
= sqlite3GetTempRange(pParse
, nPeer
);
1843 sqlite3VdbeAddOp2(v
, OP_Rowid
, pMWin
->iEphCsr
, regCRowid
);
1844 windowReadPeerValues(p
, pMWin
->iEphCsr
, regCPeer
);
1846 for(pWin
=pMWin
; pWin
; pWin
=pWin
->pNextWin
){
1847 sqlite3VdbeAddOp2(v
, OP_Null
, 0, pWin
->regAccum
);
1850 sqlite3VdbeAddOp3(v
, OP_SeekGE
, csr
, lblBrk
, pMWin
->regStartRowid
);
1852 addrNext
= sqlite3VdbeCurrentAddr(v
);
1853 sqlite3VdbeAddOp2(v
, OP_Rowid
, csr
, regRowid
);
1854 sqlite3VdbeAddOp3(v
, OP_Gt
, pMWin
->regEndRowid
, lblBrk
, regRowid
);
1855 VdbeCoverageNeverNull(v
);
1857 if( pMWin
->eExclude
==TK_CURRENT
){
1858 sqlite3VdbeAddOp3(v
, OP_Eq
, regCRowid
, lblNext
, regRowid
);
1859 VdbeCoverageNeverNull(v
);
1860 }else if( pMWin
->eExclude
!=TK_NO
){
1863 KeyInfo
*pKeyInfo
= 0;
1865 if( pMWin
->pOrderBy
){
1866 pKeyInfo
= sqlite3KeyInfoFromExprList(pParse
, pMWin
->pOrderBy
, 0, 0);
1868 if( pMWin
->eExclude
==TK_TIES
){
1869 addrEq
= sqlite3VdbeAddOp3(v
, OP_Eq
, regCRowid
, 0, regRowid
);
1870 VdbeCoverageNeverNull(v
);
1873 windowReadPeerValues(p
, csr
, regPeer
);
1874 sqlite3VdbeAddOp3(v
, OP_Compare
, regPeer
, regCPeer
, nPeer
);
1875 sqlite3VdbeAppendP4(v
, (void*)pKeyInfo
, P4_KEYINFO
);
1876 addr
= sqlite3VdbeCurrentAddr(v
)+1;
1877 sqlite3VdbeAddOp3(v
, OP_Jump
, addr
, lblNext
, addr
);
1878 VdbeCoverageEqNe(v
);
1880 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, lblNext
);
1882 if( addrEq
) sqlite3VdbeJumpHere(v
, addrEq
);
1885 windowAggStep(p
, pMWin
, csr
, 0, p
->regArg
);
1887 sqlite3VdbeResolveLabel(v
, lblNext
);
1888 sqlite3VdbeAddOp2(v
, OP_Next
, csr
, addrNext
);
1890 sqlite3VdbeJumpHere(v
, addrNext
-1);
1891 sqlite3VdbeJumpHere(v
, addrNext
+1);
1892 sqlite3ReleaseTempReg(pParse
, regRowid
);
1893 sqlite3ReleaseTempReg(pParse
, regCRowid
);
1895 sqlite3ReleaseTempRange(pParse
, regPeer
, nPeer
);
1896 sqlite3ReleaseTempRange(pParse
, regCPeer
, nPeer
);
1899 windowAggFinal(p
, 1);
1900 VdbeModuleComment((v
, "windowFullScan end"));
1904 ** Invoke the sub-routine at regGosub (generated by code in select.c) to
1905 ** return the current row of Window.iEphCsr. If all window functions are
1906 ** aggregate window functions that use the standard API, a single
1907 ** OP_Gosub instruction is all that this routine generates. Extra VM code
1908 ** for per-row processing is only generated for the following built-in window
1916 static void windowReturnOneRow(WindowCodeArg
*p
){
1917 Window
*pMWin
= p
->pMWin
;
1920 if( pMWin
->regStartRowid
){
1923 Parse
*pParse
= p
->pParse
;
1926 for(pWin
=pMWin
; pWin
; pWin
=pWin
->pNextWin
){
1927 FuncDef
*pFunc
= pWin
->pWFunc
;
1928 assert( ExprUseXList(pWin
->pOwner
) );
1929 if( pFunc
->zName
==nth_valueName
1930 || pFunc
->zName
==first_valueName
1932 int csr
= pWin
->csrApp
;
1933 int lbl
= sqlite3VdbeMakeLabel(pParse
);
1934 int tmpReg
= sqlite3GetTempReg(pParse
);
1935 sqlite3VdbeAddOp2(v
, OP_Null
, 0, pWin
->regResult
);
1937 if( pFunc
->zName
==nth_valueName
){
1938 sqlite3VdbeAddOp3(v
, OP_Column
,pMWin
->iEphCsr
,pWin
->iArgCol
+1,tmpReg
);
1939 windowCheckValue(pParse
, tmpReg
, 2);
1941 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, tmpReg
);
1943 sqlite3VdbeAddOp3(v
, OP_Add
, tmpReg
, pWin
->regApp
, tmpReg
);
1944 sqlite3VdbeAddOp3(v
, OP_Gt
, pWin
->regApp
+1, lbl
, tmpReg
);
1945 VdbeCoverageNeverNull(v
);
1946 sqlite3VdbeAddOp3(v
, OP_SeekRowid
, csr
, 0, tmpReg
);
1947 VdbeCoverageNeverTaken(v
);
1948 sqlite3VdbeAddOp3(v
, OP_Column
, csr
, pWin
->iArgCol
, pWin
->regResult
);
1949 sqlite3VdbeResolveLabel(v
, lbl
);
1950 sqlite3ReleaseTempReg(pParse
, tmpReg
);
1952 else if( pFunc
->zName
==leadName
|| pFunc
->zName
==lagName
){
1953 int nArg
= pWin
->pOwner
->x
.pList
->nExpr
;
1954 int csr
= pWin
->csrApp
;
1955 int lbl
= sqlite3VdbeMakeLabel(pParse
);
1956 int tmpReg
= sqlite3GetTempReg(pParse
);
1957 int iEph
= pMWin
->iEphCsr
;
1960 sqlite3VdbeAddOp2(v
, OP_Null
, 0, pWin
->regResult
);
1962 sqlite3VdbeAddOp3(v
, OP_Column
, iEph
,pWin
->iArgCol
+2,pWin
->regResult
);
1964 sqlite3VdbeAddOp2(v
, OP_Rowid
, iEph
, tmpReg
);
1966 int val
= (pFunc
->zName
==leadName
? 1 : -1);
1967 sqlite3VdbeAddOp2(v
, OP_AddImm
, tmpReg
, val
);
1969 int op
= (pFunc
->zName
==leadName
? OP_Add
: OP_Subtract
);
1970 int tmpReg2
= sqlite3GetTempReg(pParse
);
1971 sqlite3VdbeAddOp3(v
, OP_Column
, iEph
, pWin
->iArgCol
+1, tmpReg2
);
1972 sqlite3VdbeAddOp3(v
, op
, tmpReg2
, tmpReg
, tmpReg
);
1973 sqlite3ReleaseTempReg(pParse
, tmpReg2
);
1976 sqlite3VdbeAddOp3(v
, OP_SeekRowid
, csr
, lbl
, tmpReg
);
1978 sqlite3VdbeAddOp3(v
, OP_Column
, csr
, pWin
->iArgCol
, pWin
->regResult
);
1979 sqlite3VdbeResolveLabel(v
, lbl
);
1980 sqlite3ReleaseTempReg(pParse
, tmpReg
);
1984 sqlite3VdbeAddOp2(v
, OP_Gosub
, p
->regGosub
, p
->addrGosub
);
1988 ** Generate code to set the accumulator register for each window function
1989 ** in the linked list passed as the second argument to NULL. And perform
1990 ** any equivalent initialization required by any built-in window functions
1993 static int windowInitAccum(Parse
*pParse
, Window
*pMWin
){
1994 Vdbe
*v
= sqlite3GetVdbe(pParse
);
1998 for(pWin
=pMWin
; pWin
; pWin
=pWin
->pNextWin
){
1999 FuncDef
*pFunc
= pWin
->pWFunc
;
2000 assert( pWin
->regAccum
);
2001 sqlite3VdbeAddOp2(v
, OP_Null
, 0, pWin
->regAccum
);
2002 nArg
= MAX(nArg
, windowArgCount(pWin
));
2003 if( pMWin
->regStartRowid
==0 ){
2004 if( pFunc
->zName
==nth_valueName
|| pFunc
->zName
==first_valueName
){
2005 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, pWin
->regApp
);
2006 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, pWin
->regApp
+1);
2009 if( (pFunc
->funcFlags
& SQLITE_FUNC_MINMAX
) && pWin
->csrApp
){
2010 assert( pWin
->eStart
!=TK_UNBOUNDED
);
2011 sqlite3VdbeAddOp1(v
, OP_ResetSorter
, pWin
->csrApp
);
2012 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, pWin
->regApp
+1);
2016 regArg
= pParse
->nMem
+1;
2017 pParse
->nMem
+= nArg
;
2022 ** Return true if the current frame should be cached in the ephemeral table,
2023 ** even if there are no xInverse() calls required.
2025 static int windowCacheFrame(Window
*pMWin
){
2027 if( pMWin
->regStartRowid
) return 1;
2028 for(pWin
=pMWin
; pWin
; pWin
=pWin
->pNextWin
){
2029 FuncDef
*pFunc
= pWin
->pWFunc
;
2030 if( (pFunc
->zName
==nth_valueName
)
2031 || (pFunc
->zName
==first_valueName
)
2032 || (pFunc
->zName
==leadName
)
2033 || (pFunc
->zName
==lagName
)
2042 ** regOld and regNew are each the first register in an array of size
2043 ** pOrderBy->nExpr. This function generates code to compare the two
2044 ** arrays of registers using the collation sequences and other comparison
2045 ** parameters specified by pOrderBy.
2047 ** If the two arrays are not equal, the contents of regNew is copied to
2048 ** regOld and control falls through. Otherwise, if the contents of the arrays
2049 ** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
2051 static void windowIfNewPeer(
2054 int regNew
, /* First in array of new values */
2055 int regOld
, /* First in array of old values */
2056 int addr
/* Jump here */
2058 Vdbe
*v
= sqlite3GetVdbe(pParse
);
2060 int nVal
= pOrderBy
->nExpr
;
2061 KeyInfo
*pKeyInfo
= sqlite3KeyInfoFromExprList(pParse
, pOrderBy
, 0, 0);
2062 sqlite3VdbeAddOp3(v
, OP_Compare
, regOld
, regNew
, nVal
);
2063 sqlite3VdbeAppendP4(v
, (void*)pKeyInfo
, P4_KEYINFO
);
2064 sqlite3VdbeAddOp3(v
, OP_Jump
,
2065 sqlite3VdbeCurrentAddr(v
)+1, addr
, sqlite3VdbeCurrentAddr(v
)+1
2067 VdbeCoverageEqNe(v
);
2068 sqlite3VdbeAddOp3(v
, OP_Copy
, regNew
, regOld
, nVal
-1);
2070 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, addr
);
2075 ** This function is called as part of generating VM programs for RANGE
2076 ** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
2077 ** the ORDER BY term in the window, and that argument op is OP_Ge, it generates
2078 ** code equivalent to:
2080 ** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
2082 ** The value of parameter op may also be OP_Gt or OP_Le. In these cases the
2083 ** operator in the above pseudo-code is replaced with ">" or "<=", respectively.
2085 ** If the sort-order for the ORDER BY term in the window is DESC, then the
2086 ** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is
2087 ** subtracted. And the comparison operator is inverted to - ">=" becomes "<=",
2088 ** ">" becomes "<", and so on. So, with DESC sort order, if the argument op
2089 ** is OP_Ge, the generated code is equivalent to:
2091 ** if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;
2093 ** A special type of arithmetic is used such that if csr1.peerVal is not
2094 ** a numeric type (real or integer), then the result of the addition
2095 ** or subtraction is a a copy of csr1.peerVal.
2097 static void windowCodeRangeTest(
2099 int op
, /* OP_Ge, OP_Gt, or OP_Le */
2100 int csr1
, /* Cursor number for cursor 1 */
2101 int regVal
, /* Register containing non-negative number */
2102 int csr2
, /* Cursor number for cursor 2 */
2103 int lbl
/* Jump destination if condition is true */
2105 Parse
*pParse
= p
->pParse
;
2106 Vdbe
*v
= sqlite3GetVdbe(pParse
);
2107 ExprList
*pOrderBy
= p
->pMWin
->pOrderBy
; /* ORDER BY clause for window */
2108 int reg1
= sqlite3GetTempReg(pParse
); /* Reg. for csr1.peerVal+regVal */
2109 int reg2
= sqlite3GetTempReg(pParse
); /* Reg. for csr2.peerVal */
2110 int regString
= ++pParse
->nMem
; /* Reg. for constant value '' */
2111 int arith
= OP_Add
; /* OP_Add or OP_Subtract */
2112 int addrGe
; /* Jump destination */
2113 int addrDone
= sqlite3VdbeMakeLabel(pParse
); /* Address past OP_Ge */
2116 /* Read the peer-value from each cursor into a register */
2117 windowReadPeerValues(p
, csr1
, reg1
);
2118 windowReadPeerValues(p
, csr2
, reg2
);
2120 assert( op
==OP_Ge
|| op
==OP_Gt
|| op
==OP_Le
);
2121 assert( pOrderBy
&& pOrderBy
->nExpr
==1 );
2122 if( pOrderBy
->a
[0].fg
.sortFlags
& KEYINFO_ORDER_DESC
){
2124 case OP_Ge
: op
= OP_Le
; break;
2125 case OP_Gt
: op
= OP_Lt
; break;
2126 default: assert( op
==OP_Le
); op
= OP_Ge
; break;
2128 arith
= OP_Subtract
;
2131 VdbeModuleComment((v
, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl",
2132 reg1
, (arith
==OP_Add
? "+" : "-"), regVal
,
2133 ((op
==OP_Ge
) ? ">=" : (op
==OP_Le
) ? "<=" : (op
==OP_Gt
) ? ">" : "<"), reg2
2136 /* If the BIGNULL flag is set for the ORDER BY, then it is required to
2137 ** consider NULL values to be larger than all other values, instead of
2138 ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this
2139 ** (and adding that capability causes a performance regression), so
2140 ** instead if the BIGNULL flag is set then cases where either reg1 or
2141 ** reg2 are NULL are handled separately in the following block. The code
2142 ** generated is equivalent to:
2144 ** if( reg1 IS NULL ){
2145 ** if( op==OP_Ge ) goto lbl;
2146 ** if( op==OP_Gt && reg2 IS NOT NULL ) goto lbl;
2147 ** if( op==OP_Le && reg2 IS NULL ) goto lbl;
2148 ** }else if( reg2 IS NULL ){
2149 ** if( op==OP_Le ) goto lbl;
2152 ** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is
2153 ** not taken, control jumps over the comparison operator coded below this
2155 if( pOrderBy
->a
[0].fg
.sortFlags
& KEYINFO_ORDER_BIGNULL
){
2156 /* This block runs if reg1 contains a NULL. */
2157 int addr
= sqlite3VdbeAddOp1(v
, OP_NotNull
, reg1
); VdbeCoverage(v
);
2160 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, lbl
);
2163 sqlite3VdbeAddOp2(v
, OP_NotNull
, reg2
, lbl
);
2167 sqlite3VdbeAddOp2(v
, OP_IsNull
, reg2
, lbl
);
2170 default: assert( op
==OP_Lt
); /* no-op */ break;
2172 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, addrDone
);
2174 /* This block runs if reg1 is not NULL, but reg2 is. */
2175 sqlite3VdbeJumpHere(v
, addr
);
2176 sqlite3VdbeAddOp2(v
, OP_IsNull
, reg2
,
2177 (op
==OP_Gt
|| op
==OP_Ge
) ? addrDone
: lbl
);
2181 /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).
2182 ** This block adds (or subtracts for DESC) the numeric value in regVal
2183 ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob),
2184 ** then leave reg1 as it is. In pseudo-code, this is implemented as:
2186 ** if( reg1>='' ) goto addrGe;
2187 ** reg1 = reg1 +/- regVal
2190 ** Since all strings and blobs are greater-than-or-equal-to an empty string,
2191 ** the add/subtract is skipped for these, as required. If reg1 is a NULL,
2192 ** then the arithmetic is performed, but since adding or subtracting from
2193 ** NULL is always NULL anyway, this case is handled as required too. */
2194 sqlite3VdbeAddOp4(v
, OP_String8
, 0, regString
, 0, "", P4_STATIC
);
2195 addrGe
= sqlite3VdbeAddOp3(v
, OP_Ge
, regString
, 0, reg1
);
2197 if( (op
==OP_Ge
&& arith
==OP_Add
) || (op
==OP_Le
&& arith
==OP_Subtract
) ){
2198 sqlite3VdbeAddOp3(v
, op
, reg2
, lbl
, reg1
); VdbeCoverage(v
);
2200 sqlite3VdbeAddOp3(v
, arith
, regVal
, reg1
, reg1
);
2201 sqlite3VdbeJumpHere(v
, addrGe
);
2203 /* Compare registers reg2 and reg1, taking the jump if required. Note that
2204 ** control skips over this test if the BIGNULL flag is set and either
2205 ** reg1 or reg2 contain a NULL value. */
2206 sqlite3VdbeAddOp3(v
, op
, reg2
, lbl
, reg1
); VdbeCoverage(v
);
2207 pColl
= sqlite3ExprNNCollSeq(pParse
, pOrderBy
->a
[0].pExpr
);
2208 sqlite3VdbeAppendP4(v
, (void*)pColl
, P4_COLLSEQ
);
2209 sqlite3VdbeChangeP5(v
, SQLITE_NULLEQ
);
2210 sqlite3VdbeResolveLabel(v
, addrDone
);
2212 assert( op
==OP_Ge
|| op
==OP_Gt
|| op
==OP_Lt
|| op
==OP_Le
);
2213 testcase(op
==OP_Ge
); VdbeCoverageIf(v
, op
==OP_Ge
);
2214 testcase(op
==OP_Lt
); VdbeCoverageIf(v
, op
==OP_Lt
);
2215 testcase(op
==OP_Le
); VdbeCoverageIf(v
, op
==OP_Le
);
2216 testcase(op
==OP_Gt
); VdbeCoverageIf(v
, op
==OP_Gt
);
2217 sqlite3ReleaseTempReg(pParse
, reg1
);
2218 sqlite3ReleaseTempReg(pParse
, reg2
);
2220 VdbeModuleComment((v
, "CodeRangeTest: end"));
2224 ** Helper function for sqlite3WindowCodeStep(). Each call to this function
2225 ** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
2226 ** operation. Refer to the header comment for sqlite3WindowCodeStep() for
2229 static int windowCodeOp(
2230 WindowCodeArg
*p
, /* Context object */
2231 int op
, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
2232 int regCountdown
, /* Register for OP_IfPos countdown */
2233 int jumpOnEof
/* Jump here if stepped cursor reaches EOF */
2236 Parse
*pParse
= p
->pParse
;
2237 Window
*pMWin
= p
->pMWin
;
2240 int addrContinue
= 0;
2241 int bPeer
= (pMWin
->eFrmType
!=TK_ROWS
);
2243 int lblDone
= sqlite3VdbeMakeLabel(pParse
);
2244 int addrNextRange
= 0;
2246 /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
2247 ** starts with UNBOUNDED PRECEDING. */
2248 if( op
==WINDOW_AGGINVERSE
&& pMWin
->eStart
==TK_UNBOUNDED
){
2249 assert( regCountdown
==0 && jumpOnEof
==0 );
2253 if( regCountdown
>0 ){
2254 if( pMWin
->eFrmType
==TK_RANGE
){
2255 addrNextRange
= sqlite3VdbeCurrentAddr(v
);
2256 assert( op
==WINDOW_AGGINVERSE
|| op
==WINDOW_AGGSTEP
);
2257 if( op
==WINDOW_AGGINVERSE
){
2258 if( pMWin
->eStart
==TK_FOLLOWING
){
2259 windowCodeRangeTest(
2260 p
, OP_Le
, p
->current
.csr
, regCountdown
, p
->start
.csr
, lblDone
2263 windowCodeRangeTest(
2264 p
, OP_Ge
, p
->start
.csr
, regCountdown
, p
->current
.csr
, lblDone
2268 windowCodeRangeTest(
2269 p
, OP_Gt
, p
->end
.csr
, regCountdown
, p
->current
.csr
, lblDone
2273 sqlite3VdbeAddOp3(v
, OP_IfPos
, regCountdown
, lblDone
, 1);
2278 if( op
==WINDOW_RETURN_ROW
&& pMWin
->regStartRowid
==0 ){
2279 windowAggFinal(p
, 0);
2281 addrContinue
= sqlite3VdbeCurrentAddr(v
);
2283 /* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or
2284 ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the
2285 ** start cursor does not advance past the end cursor within the
2286 ** temporary table. It otherwise might, if (a>b). Also ensure that,
2287 ** if the input cursor is still finding new rows, that the end
2288 ** cursor does not go past it to EOF. */
2289 if( pMWin
->eStart
==pMWin
->eEnd
&& regCountdown
2290 && pMWin
->eFrmType
==TK_RANGE
2292 int regRowid1
= sqlite3GetTempReg(pParse
);
2293 int regRowid2
= sqlite3GetTempReg(pParse
);
2294 if( op
==WINDOW_AGGINVERSE
){
2295 sqlite3VdbeAddOp2(v
, OP_Rowid
, p
->start
.csr
, regRowid1
);
2296 sqlite3VdbeAddOp2(v
, OP_Rowid
, p
->end
.csr
, regRowid2
);
2297 sqlite3VdbeAddOp3(v
, OP_Ge
, regRowid2
, lblDone
, regRowid1
);
2299 }else if( p
->regRowid
){
2300 sqlite3VdbeAddOp2(v
, OP_Rowid
, p
->end
.csr
, regRowid1
);
2301 sqlite3VdbeAddOp3(v
, OP_Ge
, p
->regRowid
, lblDone
, regRowid1
);
2302 VdbeCoverageNeverNull(v
);
2304 sqlite3ReleaseTempReg(pParse
, regRowid1
);
2305 sqlite3ReleaseTempReg(pParse
, regRowid2
);
2306 assert( pMWin
->eStart
==TK_PRECEDING
|| pMWin
->eStart
==TK_FOLLOWING
);
2310 case WINDOW_RETURN_ROW
:
2311 csr
= p
->current
.csr
;
2312 reg
= p
->current
.reg
;
2313 windowReturnOneRow(p
);
2316 case WINDOW_AGGINVERSE
:
2319 if( pMWin
->regStartRowid
){
2320 assert( pMWin
->regEndRowid
);
2321 sqlite3VdbeAddOp2(v
, OP_AddImm
, pMWin
->regStartRowid
, 1);
2323 windowAggStep(p
, pMWin
, csr
, 1, p
->regArg
);
2328 assert( op
==WINDOW_AGGSTEP
);
2331 if( pMWin
->regStartRowid
){
2332 assert( pMWin
->regEndRowid
);
2333 sqlite3VdbeAddOp2(v
, OP_AddImm
, pMWin
->regEndRowid
, 1);
2335 windowAggStep(p
, pMWin
, csr
, 0, p
->regArg
);
2340 if( op
==p
->eDelete
){
2341 sqlite3VdbeAddOp1(v
, OP_Delete
, csr
);
2342 sqlite3VdbeChangeP5(v
, OPFLAG_SAVEPOSITION
);
2346 sqlite3VdbeAddOp2(v
, OP_Next
, csr
, sqlite3VdbeCurrentAddr(v
)+2);
2348 ret
= sqlite3VdbeAddOp0(v
, OP_Goto
);
2350 sqlite3VdbeAddOp2(v
, OP_Next
, csr
, sqlite3VdbeCurrentAddr(v
)+1+bPeer
);
2353 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, lblDone
);
2358 int nReg
= (pMWin
->pOrderBy
? pMWin
->pOrderBy
->nExpr
: 0);
2359 int regTmp
= (nReg
? sqlite3GetTempRange(pParse
, nReg
) : 0);
2360 windowReadPeerValues(p
, csr
, regTmp
);
2361 windowIfNewPeer(pParse
, pMWin
->pOrderBy
, regTmp
, reg
, addrContinue
);
2362 sqlite3ReleaseTempRange(pParse
, regTmp
, nReg
);
2365 if( addrNextRange
){
2366 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, addrNextRange
);
2368 sqlite3VdbeResolveLabel(v
, lblDone
);
2374 ** Allocate and return a duplicate of the Window object indicated by the
2375 ** third argument. Set the Window.pOwner field of the new object to
2378 Window
*sqlite3WindowDup(sqlite3
*db
, Expr
*pOwner
, Window
*p
){
2381 pNew
= sqlite3DbMallocZero(db
, sizeof(Window
));
2383 pNew
->zName
= sqlite3DbStrDup(db
, p
->zName
);
2384 pNew
->zBase
= sqlite3DbStrDup(db
, p
->zBase
);
2385 pNew
->pFilter
= sqlite3ExprDup(db
, p
->pFilter
, 0);
2386 pNew
->pWFunc
= p
->pWFunc
;
2387 pNew
->pPartition
= sqlite3ExprListDup(db
, p
->pPartition
, 0);
2388 pNew
->pOrderBy
= sqlite3ExprListDup(db
, p
->pOrderBy
, 0);
2389 pNew
->eFrmType
= p
->eFrmType
;
2390 pNew
->eEnd
= p
->eEnd
;
2391 pNew
->eStart
= p
->eStart
;
2392 pNew
->eExclude
= p
->eExclude
;
2393 pNew
->regResult
= p
->regResult
;
2394 pNew
->regAccum
= p
->regAccum
;
2395 pNew
->iArgCol
= p
->iArgCol
;
2396 pNew
->iEphCsr
= p
->iEphCsr
;
2397 pNew
->bExprArgs
= p
->bExprArgs
;
2398 pNew
->pStart
= sqlite3ExprDup(db
, p
->pStart
, 0);
2399 pNew
->pEnd
= sqlite3ExprDup(db
, p
->pEnd
, 0);
2400 pNew
->pOwner
= pOwner
;
2401 pNew
->bImplicitFrame
= p
->bImplicitFrame
;
2408 ** Return a copy of the linked list of Window objects passed as the
2411 Window
*sqlite3WindowListDup(sqlite3
*db
, Window
*p
){
2414 Window
**pp
= &pRet
;
2416 for(pWin
=p
; pWin
; pWin
=pWin
->pNextWin
){
2417 *pp
= sqlite3WindowDup(db
, 0, pWin
);
2419 pp
= &((*pp
)->pNextWin
);
2426 ** Return true if it can be determined at compile time that expression
2427 ** pExpr evaluates to a value that, when cast to an integer, is greater
2428 ** than zero. False otherwise.
2430 ** If an OOM error occurs, this function sets the Parse.db.mallocFailed
2431 ** flag and returns zero.
2433 static int windowExprGtZero(Parse
*pParse
, Expr
*pExpr
){
2435 sqlite3
*db
= pParse
->db
;
2436 sqlite3_value
*pVal
= 0;
2437 sqlite3ValueFromExpr(db
, pExpr
, db
->enc
, SQLITE_AFF_NUMERIC
, &pVal
);
2438 if( pVal
&& sqlite3_value_int(pVal
)>0 ){
2441 sqlite3ValueFree(pVal
);
2446 ** sqlite3WhereBegin() has already been called for the SELECT statement
2447 ** passed as the second argument when this function is invoked. It generates
2448 ** code to populate the Window.regResult register for each window function
2449 ** and invoke the sub-routine at instruction addrGosub once for each row.
2450 ** sqlite3WhereEnd() is always called before returning.
2452 ** This function handles several different types of window frames, which
2453 ** require slightly different processing. The following pseudo code is
2454 ** used to implement window frames of the form:
2456 ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
2458 ** Other window frame types use variants of the following:
2460 ** ... loop started by sqlite3WhereBegin() ...
2461 ** if( new partition ){
2464 ** Insert new row into eph table.
2466 ** if( first row of partition ){
2467 ** // Rewind three cursors, all open on the eph table.
2469 ** Rewind(csrStart);
2470 ** Rewind(csrCurrent);
2472 ** regEnd = <expr2> // FOLLOWING expression
2473 ** regStart = <expr1> // PRECEDING expression
2475 ** // First time this branch is taken, the eph table contains two
2476 ** // rows. The first row in the partition, which all three cursors
2477 ** // currently point to, and the following row.
2479 ** if( (regEnd--)<=0 ){
2481 ** if( (regStart--)<=0 ){
2491 ** if( csrCurrent is EOF ) break;
2492 ** if( (regStart--)<=0 ){
2493 ** AggInverse(csrStart)
2498 ** The pseudo-code above uses the following shorthand:
2500 ** AGGSTEP: invoke the aggregate xStep() function for each window function
2501 ** with arguments read from the current row of cursor csrEnd, then
2502 ** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
2504 ** RETURN_ROW: return a row to the caller based on the contents of the
2505 ** current row of csrCurrent and the current state of all
2506 ** aggregates. Then step cursor csrCurrent forward one row.
2508 ** AGGINVERSE: invoke the aggregate xInverse() function for each window
2509 ** functions with arguments read from the current row of cursor
2510 ** csrStart. Then step csrStart forward one row.
2512 ** There are two other ROWS window frames that are handled significantly
2513 ** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
2514 ** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
2515 ** cases because they change the order in which the three cursors (csrStart,
2516 ** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
2517 ** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
2520 ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2522 ** ... loop started by sqlite3WhereBegin() ...
2523 ** if( new partition ){
2526 ** Insert new row into eph table.
2527 ** if( first row of partition ){
2528 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2530 ** regStart = <expr1>
2532 ** if( (regEnd--)<=0 ){
2536 ** if( (regStart--)<=0 ){
2542 ** if( (regEnd--)<=0 ){
2548 ** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2550 ** ... loop started by sqlite3WhereBegin() ...
2551 ** if( new partition ){
2554 ** Insert new row into eph table.
2555 ** if( first row of partition ){
2556 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2558 ** regStart = regEnd - <expr1>
2561 ** if( (regEnd--)<=0 ){
2564 ** if( (regStart--)<=0 ){
2572 ** if( (regEnd--)<=0 ){
2576 ** if( (regStart--)<=0 ){
2581 ** while( !eof csrCurrent ){
2585 ** For the most part, the patterns above are adapted to support UNBOUNDED by
2586 ** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
2587 ** CURRENT ROW by assuming that it is equivalent to "0 PRECEDING/FOLLOWING".
2588 ** This is optimized of course - branches that will never be taken and
2589 ** conditions that are always true are omitted from the VM code. The only
2590 ** exceptional case is:
2592 ** ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
2594 ** ... loop started by sqlite3WhereBegin() ...
2595 ** if( new partition ){
2598 ** Insert new row into eph table.
2599 ** if( first row of partition ){
2600 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2601 ** regStart = <expr1>
2609 ** if( (regStart--)<=0 ){
2615 ** while( !eof csrCurrent ){
2619 ** Also requiring special handling are the cases:
2621 ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2622 ** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2624 ** when (expr1 < expr2). This is detected at runtime, not by this function.
2625 ** To handle this case, the pseudo-code programs depicted above are modified
2628 ** ... loop started by sqlite3WhereBegin() ...
2629 ** if( new partition ){
2632 ** Insert new row into eph table.
2633 ** if( first row of partition ){
2634 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2636 ** regStart = <expr1>
2637 ** if( regEnd < regStart ){
2639 ** delete eph table contents
2644 ** The new "continue" statement in the above jumps to the next iteration
2645 ** of the outer loop - the one started by sqlite3WhereBegin().
2647 ** The various GROUPS cases are implemented using the same patterns as
2648 ** ROWS. The VM code is modified slightly so that:
2650 ** 1. The else branch in the main loop is only taken if the row just
2651 ** added to the ephemeral table is the start of a new group. In
2652 ** other words, it becomes:
2654 ** ... loop started by sqlite3WhereBegin() ...
2655 ** if( new partition ){
2658 ** Insert new row into eph table.
2659 ** if( first row of partition ){
2660 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2662 ** regStart = <expr1>
2663 ** }else if( new group ){
2668 ** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
2669 ** AGGINVERSE step processes the current row of the relevant cursor and
2670 ** all subsequent rows belonging to the same group.
2672 ** RANGE window frames are a little different again. As for GROUPS, the
2673 ** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
2674 ** deal in groups instead of rows. As for ROWS and GROUPS, there are three
2677 ** RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
2679 ** ... loop started by sqlite3WhereBegin() ...
2680 ** if( new partition ){
2683 ** Insert new row into eph table.
2684 ** if( first row of partition ){
2685 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2687 ** regStart = <expr1>
2690 ** while( (csrCurrent.key + regEnd) < csrEnd.key ){
2692 ** while( csrStart.key + regStart) < csrCurrent.key ){
2702 ** if( csrCurrent is EOF ) break;
2703 ** while( csrStart.key + regStart) < csrCurrent.key ){
2709 ** In the above notation, "csr.key" means the current value of the ORDER BY
2710 ** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
2711 ** or <expr PRECEDING) read from cursor csr.
2713 ** RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2715 ** ... loop started by sqlite3WhereBegin() ...
2716 ** if( new partition ){
2719 ** Insert new row into eph table.
2720 ** if( first row of partition ){
2721 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2723 ** regStart = <expr1>
2725 ** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
2728 ** while( (csrStart.key + regStart) < csrCurrent.key ){
2735 ** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
2738 ** while( (csrStart.key + regStart) < csrCurrent.key ){
2743 ** RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2745 ** ... loop started by sqlite3WhereBegin() ...
2746 ** if( new partition ){
2749 ** Insert new row into eph table.
2750 ** if( first row of partition ){
2751 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2753 ** regStart = <expr1>
2756 ** while( (csrCurrent.key + regEnd) < csrEnd.key ){
2757 ** while( (csrCurrent.key + regStart) > csrStart.key ){
2767 ** while( (csrCurrent.key + regStart) > csrStart.key ){
2769 ** if( eof ) break "while( 1 )" loop.
2773 ** while( !eof csrCurrent ){
2777 ** The text above leaves out many details. Refer to the code and comments
2778 ** below for a more complete picture.
2780 void sqlite3WindowCodeStep(
2781 Parse
*pParse
, /* Parse context */
2782 Select
*p
, /* Rewritten SELECT statement */
2783 WhereInfo
*pWInfo
, /* Context returned by sqlite3WhereBegin() */
2784 int regGosub
, /* Register for OP_Gosub */
2785 int addrGosub
/* OP_Gosub here to return each row */
2787 Window
*pMWin
= p
->pWin
;
2788 ExprList
*pOrderBy
= pMWin
->pOrderBy
;
2789 Vdbe
*v
= sqlite3GetVdbe(pParse
);
2790 int csrWrite
; /* Cursor used to write to eph. table */
2791 int csrInput
= p
->pSrc
->a
[0].iCursor
; /* Cursor of sub-select */
2792 int nInput
= p
->pSrc
->a
[0].pTab
->nCol
; /* Number of cols returned by sub */
2793 int iInput
; /* To iterate through sub cols */
2794 int addrNe
; /* Address of OP_Ne */
2795 int addrGosubFlush
= 0; /* Address of OP_Gosub to flush: */
2796 int addrInteger
= 0; /* Address of OP_Integer */
2797 int addrEmpty
; /* Address of OP_Rewind in flush: */
2798 int regNew
; /* Array of registers holding new input row */
2799 int regRecord
; /* regNew array in record form */
2800 int regNewPeer
= 0; /* Peer values for new row (part of regNew) */
2801 int regPeer
= 0; /* Peer values for current row */
2802 int regFlushPart
= 0; /* Register for "Gosub flush_partition" */
2803 WindowCodeArg s
; /* Context object for sub-routines */
2804 int lblWhereEnd
; /* Label just before sqlite3WhereEnd() code */
2805 int regStart
= 0; /* Value of <expr> PRECEDING */
2806 int regEnd
= 0; /* Value of <expr> FOLLOWING */
2808 assert( pMWin
->eStart
==TK_PRECEDING
|| pMWin
->eStart
==TK_CURRENT
2809 || pMWin
->eStart
==TK_FOLLOWING
|| pMWin
->eStart
==TK_UNBOUNDED
2811 assert( pMWin
->eEnd
==TK_FOLLOWING
|| pMWin
->eEnd
==TK_CURRENT
2812 || pMWin
->eEnd
==TK_UNBOUNDED
|| pMWin
->eEnd
==TK_PRECEDING
2814 assert( pMWin
->eExclude
==0 || pMWin
->eExclude
==TK_CURRENT
2815 || pMWin
->eExclude
==TK_GROUP
|| pMWin
->eExclude
==TK_TIES
2816 || pMWin
->eExclude
==TK_NO
2819 lblWhereEnd
= sqlite3VdbeMakeLabel(pParse
);
2821 /* Fill in the context object */
2822 memset(&s
, 0, sizeof(WindowCodeArg
));
2826 s
.regGosub
= regGosub
;
2827 s
.addrGosub
= addrGosub
;
2828 s
.current
.csr
= pMWin
->iEphCsr
;
2829 csrWrite
= s
.current
.csr
+1;
2830 s
.start
.csr
= s
.current
.csr
+2;
2831 s
.end
.csr
= s
.current
.csr
+3;
2833 /* Figure out when rows may be deleted from the ephemeral table. There
2834 ** are four options - they may never be deleted (eDelete==0), they may
2835 ** be deleted as soon as they are no longer part of the window frame
2836 ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
2837 ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
2838 ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
2839 switch( pMWin
->eStart
){
2841 if( pMWin
->eFrmType
!=TK_RANGE
2842 && windowExprGtZero(pParse
, pMWin
->pStart
)
2844 s
.eDelete
= WINDOW_RETURN_ROW
;
2848 if( windowCacheFrame(pMWin
)==0 ){
2849 if( pMWin
->eEnd
==TK_PRECEDING
){
2850 if( pMWin
->eFrmType
!=TK_RANGE
2851 && windowExprGtZero(pParse
, pMWin
->pEnd
)
2853 s
.eDelete
= WINDOW_AGGSTEP
;
2856 s
.eDelete
= WINDOW_RETURN_ROW
;
2861 s
.eDelete
= WINDOW_AGGINVERSE
;
2865 /* Allocate registers for the array of values from the sub-query, the
2866 ** same values in record form, and the rowid used to insert said record
2867 ** into the ephemeral table. */
2868 regNew
= pParse
->nMem
+1;
2869 pParse
->nMem
+= nInput
;
2870 regRecord
= ++pParse
->nMem
;
2871 s
.regRowid
= ++pParse
->nMem
;
2873 /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
2874 ** clause, allocate registers to store the results of evaluating each
2876 if( pMWin
->eStart
==TK_PRECEDING
|| pMWin
->eStart
==TK_FOLLOWING
){
2877 regStart
= ++pParse
->nMem
;
2879 if( pMWin
->eEnd
==TK_PRECEDING
|| pMWin
->eEnd
==TK_FOLLOWING
){
2880 regEnd
= ++pParse
->nMem
;
2883 /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
2884 ** registers to store copies of the ORDER BY expressions (peer values)
2885 ** for the main loop, and for each cursor (start, current and end). */
2886 if( pMWin
->eFrmType
!=TK_ROWS
){
2887 int nPeer
= (pOrderBy
? pOrderBy
->nExpr
: 0);
2888 regNewPeer
= regNew
+ pMWin
->nBufferCol
;
2889 if( pMWin
->pPartition
) regNewPeer
+= pMWin
->pPartition
->nExpr
;
2890 regPeer
= pParse
->nMem
+1; pParse
->nMem
+= nPeer
;
2891 s
.start
.reg
= pParse
->nMem
+1; pParse
->nMem
+= nPeer
;
2892 s
.current
.reg
= pParse
->nMem
+1; pParse
->nMem
+= nPeer
;
2893 s
.end
.reg
= pParse
->nMem
+1; pParse
->nMem
+= nPeer
;
2896 /* Load the column values for the row returned by the sub-select
2897 ** into an array of registers starting at regNew. Assemble them into
2898 ** a record in register regRecord. */
2899 for(iInput
=0; iInput
<nInput
; iInput
++){
2900 sqlite3VdbeAddOp3(v
, OP_Column
, csrInput
, iInput
, regNew
+iInput
);
2902 sqlite3VdbeAddOp3(v
, OP_MakeRecord
, regNew
, nInput
, regRecord
);
2904 /* An input row has just been read into an array of registers starting
2905 ** at regNew. If the window has a PARTITION clause, this block generates
2906 ** VM code to check if the input row is the start of a new partition.
2907 ** If so, it does an OP_Gosub to an address to be filled in later. The
2908 ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
2909 if( pMWin
->pPartition
){
2911 ExprList
*pPart
= pMWin
->pPartition
;
2912 int nPart
= pPart
->nExpr
;
2913 int regNewPart
= regNew
+ pMWin
->nBufferCol
;
2914 KeyInfo
*pKeyInfo
= sqlite3KeyInfoFromExprList(pParse
, pPart
, 0, 0);
2916 regFlushPart
= ++pParse
->nMem
;
2917 addr
= sqlite3VdbeAddOp3(v
, OP_Compare
, regNewPart
, pMWin
->regPart
, nPart
);
2918 sqlite3VdbeAppendP4(v
, (void*)pKeyInfo
, P4_KEYINFO
);
2919 sqlite3VdbeAddOp3(v
, OP_Jump
, addr
+2, addr
+4, addr
+2);
2920 VdbeCoverageEqNe(v
);
2921 addrGosubFlush
= sqlite3VdbeAddOp1(v
, OP_Gosub
, regFlushPart
);
2922 VdbeComment((v
, "call flush_partition"));
2923 sqlite3VdbeAddOp3(v
, OP_Copy
, regNewPart
, pMWin
->regPart
, nPart
-1);
2926 /* Insert the new row into the ephemeral table */
2927 sqlite3VdbeAddOp2(v
, OP_NewRowid
, csrWrite
, s
.regRowid
);
2928 sqlite3VdbeAddOp3(v
, OP_Insert
, csrWrite
, regRecord
, s
.regRowid
);
2929 addrNe
= sqlite3VdbeAddOp3(v
, OP_Ne
, pMWin
->regOne
, 0, s
.regRowid
);
2930 VdbeCoverageNeverNull(v
);
2932 /* This block is run for the first row of each partition */
2933 s
.regArg
= windowInitAccum(pParse
, pMWin
);
2936 sqlite3ExprCode(pParse
, pMWin
->pStart
, regStart
);
2937 windowCheckValue(pParse
, regStart
, 0 + (pMWin
->eFrmType
==TK_RANGE
?3:0));
2940 sqlite3ExprCode(pParse
, pMWin
->pEnd
, regEnd
);
2941 windowCheckValue(pParse
, regEnd
, 1 + (pMWin
->eFrmType
==TK_RANGE
?3:0));
2944 if( pMWin
->eFrmType
!=TK_RANGE
&& pMWin
->eStart
==pMWin
->eEnd
&& regStart
){
2945 int op
= ((pMWin
->eStart
==TK_FOLLOWING
) ? OP_Ge
: OP_Le
);
2946 int addrGe
= sqlite3VdbeAddOp3(v
, op
, regStart
, 0, regEnd
);
2947 VdbeCoverageNeverNullIf(v
, op
==OP_Ge
); /* NeverNull because bound <expr> */
2948 VdbeCoverageNeverNullIf(v
, op
==OP_Le
); /* values previously checked */
2949 windowAggFinal(&s
, 0);
2950 sqlite3VdbeAddOp1(v
, OP_Rewind
, s
.current
.csr
);
2951 windowReturnOneRow(&s
);
2952 sqlite3VdbeAddOp1(v
, OP_ResetSorter
, s
.current
.csr
);
2953 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, lblWhereEnd
);
2954 sqlite3VdbeJumpHere(v
, addrGe
);
2956 if( pMWin
->eStart
==TK_FOLLOWING
&& pMWin
->eFrmType
!=TK_RANGE
&& regEnd
){
2957 assert( pMWin
->eEnd
==TK_FOLLOWING
);
2958 sqlite3VdbeAddOp3(v
, OP_Subtract
, regStart
, regEnd
, regStart
);
2961 if( pMWin
->eStart
!=TK_UNBOUNDED
){
2962 sqlite3VdbeAddOp1(v
, OP_Rewind
, s
.start
.csr
);
2964 sqlite3VdbeAddOp1(v
, OP_Rewind
, s
.current
.csr
);
2965 sqlite3VdbeAddOp1(v
, OP_Rewind
, s
.end
.csr
);
2966 if( regPeer
&& pOrderBy
){
2967 sqlite3VdbeAddOp3(v
, OP_Copy
, regNewPeer
, regPeer
, pOrderBy
->nExpr
-1);
2968 sqlite3VdbeAddOp3(v
, OP_Copy
, regPeer
, s
.start
.reg
, pOrderBy
->nExpr
-1);
2969 sqlite3VdbeAddOp3(v
, OP_Copy
, regPeer
, s
.current
.reg
, pOrderBy
->nExpr
-1);
2970 sqlite3VdbeAddOp3(v
, OP_Copy
, regPeer
, s
.end
.reg
, pOrderBy
->nExpr
-1);
2973 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, lblWhereEnd
);
2975 sqlite3VdbeJumpHere(v
, addrNe
);
2977 /* Beginning of the block executed for the second and subsequent rows. */
2979 windowIfNewPeer(pParse
, pOrderBy
, regNewPeer
, regPeer
, lblWhereEnd
);
2981 if( pMWin
->eStart
==TK_FOLLOWING
){
2982 windowCodeOp(&s
, WINDOW_AGGSTEP
, 0, 0);
2983 if( pMWin
->eEnd
!=TK_UNBOUNDED
){
2984 if( pMWin
->eFrmType
==TK_RANGE
){
2985 int lbl
= sqlite3VdbeMakeLabel(pParse
);
2986 int addrNext
= sqlite3VdbeCurrentAddr(v
);
2987 windowCodeRangeTest(&s
, OP_Ge
, s
.current
.csr
, regEnd
, s
.end
.csr
, lbl
);
2988 windowCodeOp(&s
, WINDOW_AGGINVERSE
, regStart
, 0);
2989 windowCodeOp(&s
, WINDOW_RETURN_ROW
, 0, 0);
2990 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, addrNext
);
2991 sqlite3VdbeResolveLabel(v
, lbl
);
2993 windowCodeOp(&s
, WINDOW_RETURN_ROW
, regEnd
, 0);
2994 windowCodeOp(&s
, WINDOW_AGGINVERSE
, regStart
, 0);
2998 if( pMWin
->eEnd
==TK_PRECEDING
){
2999 int bRPS
= (pMWin
->eStart
==TK_PRECEDING
&& pMWin
->eFrmType
==TK_RANGE
);
3000 windowCodeOp(&s
, WINDOW_AGGSTEP
, regEnd
, 0);
3001 if( bRPS
) windowCodeOp(&s
, WINDOW_AGGINVERSE
, regStart
, 0);
3002 windowCodeOp(&s
, WINDOW_RETURN_ROW
, 0, 0);
3003 if( !bRPS
) windowCodeOp(&s
, WINDOW_AGGINVERSE
, regStart
, 0);
3006 windowCodeOp(&s
, WINDOW_AGGSTEP
, 0, 0);
3007 if( pMWin
->eEnd
!=TK_UNBOUNDED
){
3008 if( pMWin
->eFrmType
==TK_RANGE
){
3010 addr
= sqlite3VdbeCurrentAddr(v
);
3012 lbl
= sqlite3VdbeMakeLabel(pParse
);
3013 windowCodeRangeTest(&s
, OP_Ge
, s
.current
.csr
, regEnd
, s
.end
.csr
, lbl
);
3015 windowCodeOp(&s
, WINDOW_RETURN_ROW
, 0, 0);
3016 windowCodeOp(&s
, WINDOW_AGGINVERSE
, regStart
, 0);
3018 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, addr
);
3019 sqlite3VdbeResolveLabel(v
, lbl
);
3023 addr
= sqlite3VdbeAddOp3(v
, OP_IfPos
, regEnd
, 0, 1);
3026 windowCodeOp(&s
, WINDOW_RETURN_ROW
, 0, 0);
3027 windowCodeOp(&s
, WINDOW_AGGINVERSE
, regStart
, 0);
3028 if( regEnd
) sqlite3VdbeJumpHere(v
, addr
);
3033 /* End of the main input loop */
3034 sqlite3VdbeResolveLabel(v
, lblWhereEnd
);
3035 sqlite3WhereEnd(pWInfo
);
3038 if( pMWin
->pPartition
){
3039 addrInteger
= sqlite3VdbeAddOp2(v
, OP_Integer
, 0, regFlushPart
);
3040 sqlite3VdbeJumpHere(v
, addrGosubFlush
);
3044 addrEmpty
= sqlite3VdbeAddOp1(v
, OP_Rewind
, csrWrite
);
3046 if( pMWin
->eEnd
==TK_PRECEDING
){
3047 int bRPS
= (pMWin
->eStart
==TK_PRECEDING
&& pMWin
->eFrmType
==TK_RANGE
);
3048 windowCodeOp(&s
, WINDOW_AGGSTEP
, regEnd
, 0);
3049 if( bRPS
) windowCodeOp(&s
, WINDOW_AGGINVERSE
, regStart
, 0);
3050 windowCodeOp(&s
, WINDOW_RETURN_ROW
, 0, 0);
3051 }else if( pMWin
->eStart
==TK_FOLLOWING
){
3056 windowCodeOp(&s
, WINDOW_AGGSTEP
, 0, 0);
3057 if( pMWin
->eFrmType
==TK_RANGE
){
3058 addrStart
= sqlite3VdbeCurrentAddr(v
);
3059 addrBreak2
= windowCodeOp(&s
, WINDOW_AGGINVERSE
, regStart
, 1);
3060 addrBreak1
= windowCodeOp(&s
, WINDOW_RETURN_ROW
, 0, 1);
3062 if( pMWin
->eEnd
==TK_UNBOUNDED
){
3063 addrStart
= sqlite3VdbeCurrentAddr(v
);
3064 addrBreak1
= windowCodeOp(&s
, WINDOW_RETURN_ROW
, regStart
, 1);
3065 addrBreak2
= windowCodeOp(&s
, WINDOW_AGGINVERSE
, 0, 1);
3067 assert( pMWin
->eEnd
==TK_FOLLOWING
);
3068 addrStart
= sqlite3VdbeCurrentAddr(v
);
3069 addrBreak1
= windowCodeOp(&s
, WINDOW_RETURN_ROW
, regEnd
, 1);
3070 addrBreak2
= windowCodeOp(&s
, WINDOW_AGGINVERSE
, regStart
, 1);
3072 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, addrStart
);
3073 sqlite3VdbeJumpHere(v
, addrBreak2
);
3074 addrStart
= sqlite3VdbeCurrentAddr(v
);
3075 addrBreak3
= windowCodeOp(&s
, WINDOW_RETURN_ROW
, 0, 1);
3076 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, addrStart
);
3077 sqlite3VdbeJumpHere(v
, addrBreak1
);
3078 sqlite3VdbeJumpHere(v
, addrBreak3
);
3082 windowCodeOp(&s
, WINDOW_AGGSTEP
, 0, 0);
3083 addrStart
= sqlite3VdbeCurrentAddr(v
);
3084 addrBreak
= windowCodeOp(&s
, WINDOW_RETURN_ROW
, 0, 1);
3085 windowCodeOp(&s
, WINDOW_AGGINVERSE
, regStart
, 0);
3086 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, addrStart
);
3087 sqlite3VdbeJumpHere(v
, addrBreak
);
3089 sqlite3VdbeJumpHere(v
, addrEmpty
);
3091 sqlite3VdbeAddOp1(v
, OP_ResetSorter
, s
.current
.csr
);
3092 if( pMWin
->pPartition
){
3093 if( pMWin
->regStartRowid
){
3094 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, pMWin
->regStartRowid
);
3095 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, pMWin
->regEndRowid
);
3097 sqlite3VdbeChangeP1(v
, addrInteger
, sqlite3VdbeCurrentAddr(v
));
3098 sqlite3VdbeAddOp1(v
, OP_Return
, regFlushPart
);
3102 #endif /* SQLITE_OMIT_WINDOWFUNC */