1 /* 2 ** 2018 May 08 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ************************************************************************* 12 */ 13 #include "sqliteInt.h" 14 15 #ifndef SQLITE_OMIT_WINDOWFUNC 16 17 /* 18 ** SELECT REWRITING 19 ** 20 ** Any SELECT statement that contains one or more window functions in 21 ** either the select list or ORDER BY clause (the only two places window 22 ** functions may be used) is transformed by function sqlite3WindowRewrite() 23 ** in order to support window function processing. For example, with the 24 ** schema: 25 ** 26 ** CREATE TABLE t1(a, b, c, d, e, f, g); 27 ** 28 ** the statement: 29 ** 30 ** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e; 31 ** 32 ** is transformed to: 33 ** 34 ** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM ( 35 ** SELECT a, e, c, d, b FROM t1 ORDER BY c, d 36 ** ) ORDER BY e; 37 ** 38 ** The flattening optimization is disabled when processing this transformed 39 ** SELECT statement. This allows the implementation of the window function 40 ** (in this case max()) to process rows sorted in order of (c, d), which 41 ** makes things easier for obvious reasons. More generally: 42 ** 43 ** * FROM, WHERE, GROUP BY and HAVING clauses are all moved to 44 ** the sub-query. 45 ** 46 ** * ORDER BY, LIMIT and OFFSET remain part of the parent query. 47 ** 48 ** * Terminals from each of the expression trees that make up the 49 ** select-list and ORDER BY expressions in the parent query are 50 ** selected by the sub-query. For the purposes of the transformation, 51 ** terminals are column references and aggregate functions. 52 ** 53 ** If there is more than one window function in the SELECT that uses 54 ** the same window declaration (the OVER bit), then a single scan may 55 ** be used to process more than one window function. For example: 56 ** 57 ** SELECT max(b) OVER (PARTITION BY c ORDER BY d), 58 ** min(e) OVER (PARTITION BY c ORDER BY d) 59 ** FROM t1; 60 ** 61 ** is transformed in the same way as the example above. However: 62 ** 63 ** SELECT max(b) OVER (PARTITION BY c ORDER BY d), 64 ** min(e) OVER (PARTITION BY a ORDER BY b) 65 ** FROM t1; 66 ** 67 ** Must be transformed to: 68 ** 69 ** SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM ( 70 ** SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM 71 ** SELECT a, e, c, d, b FROM t1 ORDER BY a, b 72 ** ) ORDER BY c, d 73 ** ) ORDER BY e; 74 ** 75 ** so that both min() and max() may process rows in the order defined by 76 ** their respective window declarations. 77 ** 78 ** INTERFACE WITH SELECT.C 79 ** 80 ** When processing the rewritten SELECT statement, code in select.c calls 81 ** sqlite3WhereBegin() to begin iterating through the results of the 82 ** sub-query, which is always implemented as a co-routine. It then calls 83 ** sqlite3WindowCodeStep() to process rows and finish the scan by calling 84 ** sqlite3WhereEnd(). 85 ** 86 ** sqlite3WindowCodeStep() generates VM code so that, for each row returned 87 ** by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked. 88 ** When the sub-routine is invoked: 89 ** 90 ** * The results of all window-functions for the row are stored 91 ** in the associated Window.regResult registers. 92 ** 93 ** * The required terminal values are stored in the current row of 94 ** temp table Window.iEphCsr. 95 ** 96 ** In some cases, depending on the window frame and the specific window 97 ** functions invoked, sqlite3WindowCodeStep() caches each entire partition 98 ** in a temp table before returning any rows. In other cases it does not. 99 ** This detail is encapsulated within this file, the code generated by 100 ** select.c is the same in either case. 101 ** 102 ** BUILT-IN WINDOW FUNCTIONS 103 ** 104 ** This implementation features the following built-in window functions: 105 ** 106 ** row_number() 107 ** rank() 108 ** dense_rank() 109 ** percent_rank() 110 ** cume_dist() 111 ** ntile(N) 112 ** lead(expr [, offset [, default]]) 113 ** lag(expr [, offset [, default]]) 114 ** first_value(expr) 115 ** last_value(expr) 116 ** nth_value(expr, N) 117 ** 118 ** These are the same built-in window functions supported by Postgres. 119 ** Although the behaviour of aggregate window functions (functions that 120 ** can be used as either aggregates or window funtions) allows them to 121 ** be implemented using an API, built-in window functions are much more 122 ** esoteric. Additionally, some window functions (e.g. nth_value()) 123 ** may only be implemented by caching the entire partition in memory. 124 ** As such, some built-in window functions use the same API as aggregate 125 ** window functions and some are implemented directly using VDBE 126 ** instructions. Additionally, for those functions that use the API, the 127 ** window frame is sometimes modified before the SELECT statement is 128 ** rewritten. For example, regardless of the specified window frame, the 129 ** row_number() function always uses: 130 ** 131 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 132 ** 133 ** See sqlite3WindowUpdate() for details. 134 ** 135 ** As well as some of the built-in window functions, aggregate window 136 ** functions min() and max() are implemented using VDBE instructions if 137 ** the start of the window frame is declared as anything other than 138 ** UNBOUNDED PRECEDING. 139 */ 140 141 /* 142 ** Implementation of built-in window function row_number(). Assumes that the 143 ** window frame has been coerced to: 144 ** 145 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 146 */ 147 static void row_numberStepFunc( 148 sqlite3_context *pCtx, 149 int nArg, 150 sqlite3_value **apArg 151 ){ 152 i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 153 if( p ) (*p)++; 154 UNUSED_PARAMETER(nArg); 155 UNUSED_PARAMETER(apArg); 156 } 157 static void row_numberValueFunc(sqlite3_context *pCtx){ 158 i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 159 sqlite3_result_int64(pCtx, (p ? *p : 0)); 160 } 161 162 /* 163 ** Context object type used by rank(), dense_rank(), percent_rank() and 164 ** cume_dist(). 165 */ 166 struct CallCount { 167 i64 nValue; 168 i64 nStep; 169 i64 nTotal; 170 }; 171 172 /* 173 ** Implementation of built-in window function dense_rank(). Assumes that 174 ** the window frame has been set to: 175 ** 176 ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 177 */ 178 static void dense_rankStepFunc( 179 sqlite3_context *pCtx, 180 int nArg, 181 sqlite3_value **apArg 182 ){ 183 struct CallCount *p; 184 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 185 if( p ) p->nStep = 1; 186 UNUSED_PARAMETER(nArg); 187 UNUSED_PARAMETER(apArg); 188 } 189 static void dense_rankValueFunc(sqlite3_context *pCtx){ 190 struct CallCount *p; 191 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 192 if( p ){ 193 if( p->nStep ){ 194 p->nValue++; 195 p->nStep = 0; 196 } 197 sqlite3_result_int64(pCtx, p->nValue); 198 } 199 } 200 201 /* 202 ** Implementation of built-in window function rank(). Assumes that 203 ** the window frame has been set to: 204 ** 205 ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 206 */ 207 static void rankStepFunc( 208 sqlite3_context *pCtx, 209 int nArg, 210 sqlite3_value **apArg 211 ){ 212 struct CallCount *p; 213 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 214 if( p ){ 215 p->nStep++; 216 if( p->nValue==0 ){ 217 p->nValue = p->nStep; 218 } 219 } 220 UNUSED_PARAMETER(nArg); 221 UNUSED_PARAMETER(apArg); 222 } 223 static void rankValueFunc(sqlite3_context *pCtx){ 224 struct CallCount *p; 225 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 226 if( p ){ 227 sqlite3_result_int64(pCtx, p->nValue); 228 p->nValue = 0; 229 } 230 } 231 232 /* 233 ** Implementation of built-in window function percent_rank(). Assumes that 234 ** the window frame has been set to: 235 ** 236 ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 237 */ 238 static void percent_rankStepFunc( 239 sqlite3_context *pCtx, 240 int nArg, 241 sqlite3_value **apArg 242 ){ 243 struct CallCount *p; 244 UNUSED_PARAMETER(nArg); assert( nArg==1 ); 245 246 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 247 if( p ){ 248 if( p->nTotal==0 ){ 249 p->nTotal = sqlite3_value_int64(apArg[0]); 250 } 251 p->nStep++; 252 if( p->nValue==0 ){ 253 p->nValue = p->nStep; 254 } 255 } 256 } 257 static void percent_rankValueFunc(sqlite3_context *pCtx){ 258 struct CallCount *p; 259 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 260 if( p ){ 261 if( p->nTotal>1 ){ 262 double r = (double)(p->nValue-1) / (double)(p->nTotal-1); 263 sqlite3_result_double(pCtx, r); 264 }else{ 265 sqlite3_result_double(pCtx, 0.0); 266 } 267 p->nValue = 0; 268 } 269 } 270 271 /* 272 ** Implementation of built-in window function cume_dist(). Assumes that 273 ** the window frame has been set to: 274 ** 275 ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 276 */ 277 static void cume_distStepFunc( 278 sqlite3_context *pCtx, 279 int nArg, 280 sqlite3_value **apArg 281 ){ 282 struct CallCount *p; 283 assert( nArg==1 ); UNUSED_PARAMETER(nArg); 284 285 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 286 if( p ){ 287 if( p->nTotal==0 ){ 288 p->nTotal = sqlite3_value_int64(apArg[0]); 289 } 290 p->nStep++; 291 } 292 } 293 static void cume_distValueFunc(sqlite3_context *pCtx){ 294 struct CallCount *p; 295 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 296 if( p && p->nTotal ){ 297 double r = (double)(p->nStep) / (double)(p->nTotal); 298 sqlite3_result_double(pCtx, r); 299 } 300 } 301 302 /* 303 ** Context object for ntile() window function. 304 */ 305 struct NtileCtx { 306 i64 nTotal; /* Total rows in partition */ 307 i64 nParam; /* Parameter passed to ntile(N) */ 308 i64 iRow; /* Current row */ 309 }; 310 311 /* 312 ** Implementation of ntile(). This assumes that the window frame has 313 ** been coerced to: 314 ** 315 ** ROWS UNBOUNDED PRECEDING AND CURRENT ROW 316 */ 317 static void ntileStepFunc( 318 sqlite3_context *pCtx, 319 int nArg, 320 sqlite3_value **apArg 321 ){ 322 struct NtileCtx *p; 323 assert( nArg==2 ); UNUSED_PARAMETER(nArg); 324 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 325 if( p ){ 326 if( p->nTotal==0 ){ 327 p->nParam = sqlite3_value_int64(apArg[0]); 328 p->nTotal = sqlite3_value_int64(apArg[1]); 329 if( p->nParam<=0 ){ 330 sqlite3_result_error( 331 pCtx, "argument of ntile must be a positive integer", -1 332 ); 333 } 334 } 335 p->iRow++; 336 } 337 } 338 static void ntileValueFunc(sqlite3_context *pCtx){ 339 struct NtileCtx *p; 340 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 341 if( p && p->nParam>0 ){ 342 int nSize = (p->nTotal / p->nParam); 343 if( nSize==0 ){ 344 sqlite3_result_int64(pCtx, p->iRow); 345 }else{ 346 i64 nLarge = p->nTotal - p->nParam*nSize; 347 i64 iSmall = nLarge*(nSize+1); 348 i64 iRow = p->iRow-1; 349 350 assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal ); 351 352 if( iRow<iSmall ){ 353 sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1)); 354 }else{ 355 sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize); 356 } 357 } 358 } 359 } 360 361 /* 362 ** Context object for last_value() window function. 363 */ 364 struct LastValueCtx { 365 sqlite3_value *pVal; 366 int nVal; 367 }; 368 369 /* 370 ** Implementation of last_value(). 371 */ 372 static void last_valueStepFunc( 373 sqlite3_context *pCtx, 374 int nArg, 375 sqlite3_value **apArg 376 ){ 377 struct LastValueCtx *p; 378 UNUSED_PARAMETER(nArg); 379 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 380 if( p ){ 381 sqlite3_value_free(p->pVal); 382 p->pVal = sqlite3_value_dup(apArg[0]); 383 if( p->pVal==0 ){ 384 sqlite3_result_error_nomem(pCtx); 385 }else{ 386 p->nVal++; 387 } 388 } 389 } 390 static void last_valueInvFunc( 391 sqlite3_context *pCtx, 392 int nArg, 393 sqlite3_value **apArg 394 ){ 395 struct LastValueCtx *p; 396 UNUSED_PARAMETER(nArg); 397 UNUSED_PARAMETER(apArg); 398 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 399 if( ALWAYS(p) ){ 400 p->nVal--; 401 if( p->nVal==0 ){ 402 sqlite3_value_free(p->pVal); 403 p->pVal = 0; 404 } 405 } 406 } 407 static void last_valueValueFunc(sqlite3_context *pCtx){ 408 struct LastValueCtx *p; 409 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 410 if( p && p->pVal ){ 411 sqlite3_result_value(pCtx, p->pVal); 412 } 413 } 414 static void last_valueFinalizeFunc(sqlite3_context *pCtx){ 415 struct LastValueCtx *p; 416 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 417 if( p && p->pVal ){ 418 sqlite3_result_value(pCtx, p->pVal); 419 sqlite3_value_free(p->pVal); 420 p->pVal = 0; 421 } 422 } 423 424 /* 425 ** Static names for the built-in window function names. These static 426 ** names are used, rather than string literals, so that FuncDef objects 427 ** can be associated with a particular window function by direct 428 ** comparison of the zName pointer. Example: 429 ** 430 ** if( pFuncDef->zName==row_valueName ){ ... } 431 */ 432 static const char row_numberName[] = "row_number"; 433 static const char dense_rankName[] = "dense_rank"; 434 static const char rankName[] = "rank"; 435 static const char percent_rankName[] = "percent_rank"; 436 static const char cume_distName[] = "cume_dist"; 437 static const char ntileName[] = "ntile"; 438 static const char last_valueName[] = "last_value"; 439 static const char nth_valueName[] = "nth_value"; 440 static const char first_valueName[] = "first_value"; 441 static const char leadName[] = "lead"; 442 static const char lagName[] = "lag"; 443 444 /* 445 ** No-op implementations of xStep() and xFinalize(). Used as place-holders 446 ** for built-in window functions that never call those interfaces. 447 ** 448 ** The noopValueFunc() is called but is expected to do nothing. The 449 ** noopStepFunc() is never called, and so it is marked with NO_TEST to 450 ** let the test coverage routine know not to expect this function to be 451 ** invoked. 452 */ 453 static void noopStepFunc( /*NO_TEST*/ 454 sqlite3_context *p, /*NO_TEST*/ 455 int n, /*NO_TEST*/ 456 sqlite3_value **a /*NO_TEST*/ 457 ){ /*NO_TEST*/ 458 UNUSED_PARAMETER(p); /*NO_TEST*/ 459 UNUSED_PARAMETER(n); /*NO_TEST*/ 460 UNUSED_PARAMETER(a); /*NO_TEST*/ 461 assert(0); /*NO_TEST*/ 462 } /*NO_TEST*/ 463 static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ } 464 465 /* Window functions that use all window interfaces: xStep, xFinal, 466 ** xValue, and xInverse */ 467 #define WINDOWFUNCALL(name,nArg,extra) { \ 468 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \ 469 name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \ 470 name ## InvFunc, name ## Name, {0} \ 471 } 472 473 /* Window functions that are implemented using bytecode and thus have 474 ** no-op routines for their methods */ 475 #define WINDOWFUNCNOOP(name,nArg,extra) { \ 476 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \ 477 noopStepFunc, noopValueFunc, noopValueFunc, \ 478 noopStepFunc, name ## Name, {0} \ 479 } 480 481 /* Window functions that use all window interfaces: xStep, the 482 ** same routine for xFinalize and xValue and which never call 483 ** xInverse. */ 484 #define WINDOWFUNCX(name,nArg,extra) { \ 485 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \ 486 name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \ 487 noopStepFunc, name ## Name, {0} \ 488 } 489 490 491 /* 492 ** Register those built-in window functions that are not also aggregates. 493 */ 494 void sqlite3WindowFunctions(void){ 495 static FuncDef aWindowFuncs[] = { 496 WINDOWFUNCX(row_number, 0, 0), 497 WINDOWFUNCX(dense_rank, 0, 0), 498 WINDOWFUNCX(rank, 0, 0), 499 WINDOWFUNCX(percent_rank, 0, SQLITE_FUNC_WINDOW_SIZE), 500 WINDOWFUNCX(cume_dist, 0, SQLITE_FUNC_WINDOW_SIZE), 501 WINDOWFUNCX(ntile, 1, SQLITE_FUNC_WINDOW_SIZE), 502 WINDOWFUNCALL(last_value, 1, 0), 503 WINDOWFUNCNOOP(nth_value, 2, 0), 504 WINDOWFUNCNOOP(first_value, 1, 0), 505 WINDOWFUNCNOOP(lead, 1, 0), 506 WINDOWFUNCNOOP(lead, 2, 0), 507 WINDOWFUNCNOOP(lead, 3, 0), 508 WINDOWFUNCNOOP(lag, 1, 0), 509 WINDOWFUNCNOOP(lag, 2, 0), 510 WINDOWFUNCNOOP(lag, 3, 0), 511 }; 512 sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs)); 513 } 514 515 /* 516 ** This function is called immediately after resolving the function name 517 ** for a window function within a SELECT statement. Argument pList is a 518 ** linked list of WINDOW definitions for the current SELECT statement. 519 ** Argument pFunc is the function definition just resolved and pWin 520 ** is the Window object representing the associated OVER clause. This 521 ** function updates the contents of pWin as follows: 522 ** 523 ** * If the OVER clause refered to a named window (as in "max(x) OVER win"), 524 ** search list pList for a matching WINDOW definition, and update pWin 525 ** accordingly. If no such WINDOW clause can be found, leave an error 526 ** in pParse. 527 ** 528 ** * If the function is a built-in window function that requires the 529 ** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top 530 ** of this file), pWin is updated here. 531 */ 532 void sqlite3WindowUpdate( 533 Parse *pParse, 534 Window *pList, /* List of named windows for this SELECT */ 535 Window *pWin, /* Window frame to update */ 536 FuncDef *pFunc /* Window function definition */ 537 ){ 538 if( pWin->zName && pWin->eType==0 ){ 539 Window *p; 540 for(p=pList; p; p=p->pNextWin){ 541 if( sqlite3StrICmp(p->zName, pWin->zName)==0 ) break; 542 } 543 if( p==0 ){ 544 sqlite3ErrorMsg(pParse, "no such window: %s", pWin->zName); 545 return; 546 } 547 pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0); 548 pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0); 549 pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0); 550 pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0); 551 pWin->eStart = p->eStart; 552 pWin->eEnd = p->eEnd; 553 pWin->eType = p->eType; 554 } 555 if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){ 556 sqlite3 *db = pParse->db; 557 if( pWin->pFilter ){ 558 sqlite3ErrorMsg(pParse, 559 "FILTER clause may only be used with aggregate window functions" 560 ); 561 }else 562 if( pFunc->zName==row_numberName || pFunc->zName==ntileName ){ 563 sqlite3ExprDelete(db, pWin->pStart); 564 sqlite3ExprDelete(db, pWin->pEnd); 565 pWin->pStart = pWin->pEnd = 0; 566 pWin->eType = TK_ROWS; 567 pWin->eStart = TK_UNBOUNDED; 568 pWin->eEnd = TK_CURRENT; 569 }else 570 571 if( pFunc->zName==dense_rankName || pFunc->zName==rankName 572 || pFunc->zName==percent_rankName || pFunc->zName==cume_distName 573 ){ 574 sqlite3ExprDelete(db, pWin->pStart); 575 sqlite3ExprDelete(db, pWin->pEnd); 576 pWin->pStart = pWin->pEnd = 0; 577 pWin->eType = TK_RANGE; 578 pWin->eStart = TK_UNBOUNDED; 579 pWin->eEnd = TK_CURRENT; 580 } 581 } 582 pWin->pFunc = pFunc; 583 } 584 585 /* 586 ** Context object passed through sqlite3WalkExprList() to 587 ** selectWindowRewriteExprCb() by selectWindowRewriteEList(). 588 */ 589 typedef struct WindowRewrite WindowRewrite; 590 struct WindowRewrite { 591 Window *pWin; 592 SrcList *pSrc; 593 ExprList *pSub; 594 Select *pSubSelect; /* Current sub-select, if any */ 595 }; 596 597 /* 598 ** Callback function used by selectWindowRewriteEList(). If necessary, 599 ** this function appends to the output expression-list and updates 600 ** expression (*ppExpr) in place. 601 */ 602 static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){ 603 struct WindowRewrite *p = pWalker->u.pRewrite; 604 Parse *pParse = pWalker->pParse; 605 606 /* If this function is being called from within a scalar sub-select 607 ** that used by the SELECT statement being processed, only process 608 ** TK_COLUMN expressions that refer to it (the outer SELECT). Do 609 ** not process aggregates or window functions at all, as they belong 610 ** to the scalar sub-select. */ 611 if( p->pSubSelect ){ 612 if( pExpr->op!=TK_COLUMN ){ 613 return WRC_Continue; 614 }else{ 615 int nSrc = p->pSrc->nSrc; 616 int i; 617 for(i=0; i<nSrc; i++){ 618 if( pExpr->iTable==p->pSrc->a[i].iCursor ) break; 619 } 620 if( i==nSrc ) return WRC_Continue; 621 } 622 } 623 624 switch( pExpr->op ){ 625 626 case TK_FUNCTION: 627 if( pExpr->pWin==0 ){ 628 break; 629 }else{ 630 Window *pWin; 631 for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){ 632 if( pExpr->pWin==pWin ){ 633 assert( pWin->pOwner==pExpr ); 634 return WRC_Prune; 635 } 636 } 637 } 638 /* Fall through. */ 639 640 case TK_AGG_FUNCTION: 641 case TK_COLUMN: { 642 Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0); 643 p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup); 644 if( p->pSub ){ 645 assert( ExprHasProperty(pExpr, EP_Static)==0 ); 646 ExprSetProperty(pExpr, EP_Static); 647 sqlite3ExprDelete(pParse->db, pExpr); 648 ExprClearProperty(pExpr, EP_Static); 649 memset(pExpr, 0, sizeof(Expr)); 650 651 pExpr->op = TK_COLUMN; 652 pExpr->iColumn = p->pSub->nExpr-1; 653 pExpr->iTable = p->pWin->iEphCsr; 654 } 655 656 break; 657 } 658 659 default: /* no-op */ 660 break; 661 } 662 663 return WRC_Continue; 664 } 665 static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){ 666 struct WindowRewrite *p = pWalker->u.pRewrite; 667 Select *pSave = p->pSubSelect; 668 if( pSave==pSelect ){ 669 return WRC_Continue; 670 }else{ 671 p->pSubSelect = pSelect; 672 sqlite3WalkSelect(pWalker, pSelect); 673 p->pSubSelect = pSave; 674 } 675 return WRC_Prune; 676 } 677 678 679 /* 680 ** Iterate through each expression in expression-list pEList. For each: 681 ** 682 ** * TK_COLUMN, 683 ** * aggregate function, or 684 ** * window function with a Window object that is not a member of the 685 ** Window list passed as the second argument (pWin). 686 ** 687 ** Append the node to output expression-list (*ppSub). And replace it 688 ** with a TK_COLUMN that reads the (N-1)th element of table 689 ** pWin->iEphCsr, where N is the number of elements in (*ppSub) after 690 ** appending the new one. 691 */ 692 static void selectWindowRewriteEList( 693 Parse *pParse, 694 Window *pWin, 695 SrcList *pSrc, 696 ExprList *pEList, /* Rewrite expressions in this list */ 697 ExprList **ppSub /* IN/OUT: Sub-select expression-list */ 698 ){ 699 Walker sWalker; 700 WindowRewrite sRewrite; 701 702 memset(&sWalker, 0, sizeof(Walker)); 703 memset(&sRewrite, 0, sizeof(WindowRewrite)); 704 705 sRewrite.pSub = *ppSub; 706 sRewrite.pWin = pWin; 707 sRewrite.pSrc = pSrc; 708 709 sWalker.pParse = pParse; 710 sWalker.xExprCallback = selectWindowRewriteExprCb; 711 sWalker.xSelectCallback = selectWindowRewriteSelectCb; 712 sWalker.u.pRewrite = &sRewrite; 713 714 (void)sqlite3WalkExprList(&sWalker, pEList); 715 716 *ppSub = sRewrite.pSub; 717 } 718 719 /* 720 ** Append a copy of each expression in expression-list pAppend to 721 ** expression list pList. Return a pointer to the result list. 722 */ 723 static ExprList *exprListAppendList( 724 Parse *pParse, /* Parsing context */ 725 ExprList *pList, /* List to which to append. Might be NULL */ 726 ExprList *pAppend /* List of values to append. Might be NULL */ 727 ){ 728 if( pAppend ){ 729 int i; 730 int nInit = pList ? pList->nExpr : 0; 731 for(i=0; i<pAppend->nExpr; i++){ 732 Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0); 733 pList = sqlite3ExprListAppend(pParse, pList, pDup); 734 if( pList ) pList->a[nInit+i].sortOrder = pAppend->a[i].sortOrder; 735 } 736 } 737 return pList; 738 } 739 740 /* 741 ** If the SELECT statement passed as the second argument does not invoke 742 ** any SQL window functions, this function is a no-op. Otherwise, it 743 ** rewrites the SELECT statement so that window function xStep functions 744 ** are invoked in the correct order as described under "SELECT REWRITING" 745 ** at the top of this file. 746 */ 747 int sqlite3WindowRewrite(Parse *pParse, Select *p){ 748 int rc = SQLITE_OK; 749 if( p->pWin ){ 750 Vdbe *v = sqlite3GetVdbe(pParse); 751 sqlite3 *db = pParse->db; 752 Select *pSub = 0; /* The subquery */ 753 SrcList *pSrc = p->pSrc; 754 Expr *pWhere = p->pWhere; 755 ExprList *pGroupBy = p->pGroupBy; 756 Expr *pHaving = p->pHaving; 757 ExprList *pSort = 0; 758 759 ExprList *pSublist = 0; /* Expression list for sub-query */ 760 Window *pMWin = p->pWin; /* Master window object */ 761 Window *pWin; /* Window object iterator */ 762 763 p->pSrc = 0; 764 p->pWhere = 0; 765 p->pGroupBy = 0; 766 p->pHaving = 0; 767 768 /* Create the ORDER BY clause for the sub-select. This is the concatenation 769 ** of the window PARTITION and ORDER BY clauses. Then, if this makes it 770 ** redundant, remove the ORDER BY from the parent SELECT. */ 771 pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0); 772 pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy); 773 if( pSort && p->pOrderBy ){ 774 if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){ 775 sqlite3ExprListDelete(db, p->pOrderBy); 776 p->pOrderBy = 0; 777 } 778 } 779 780 /* Assign a cursor number for the ephemeral table used to buffer rows. 781 ** The OpenEphemeral instruction is coded later, after it is known how 782 ** many columns the table will have. */ 783 pMWin->iEphCsr = pParse->nTab++; 784 785 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, &pSublist); 786 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, &pSublist); 787 pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0); 788 789 /* Append the PARTITION BY and ORDER BY expressions to the to the 790 ** sub-select expression list. They are required to figure out where 791 ** boundaries for partitions and sets of peer rows lie. */ 792 pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition); 793 pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy); 794 795 /* Append the arguments passed to each window function to the 796 ** sub-select expression list. Also allocate two registers for each 797 ** window function - one for the accumulator, another for interim 798 ** results. */ 799 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 800 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0); 801 pSublist = exprListAppendList(pParse, pSublist, pWin->pOwner->x.pList); 802 if( pWin->pFilter ){ 803 Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0); 804 pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter); 805 } 806 pWin->regAccum = ++pParse->nMem; 807 pWin->regResult = ++pParse->nMem; 808 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); 809 } 810 811 /* If there is no ORDER BY or PARTITION BY clause, and the window 812 ** function accepts zero arguments, and there are no other columns 813 ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible 814 ** that pSublist is still NULL here. Add a constant expression here to 815 ** keep everything legal in this case. 816 */ 817 if( pSublist==0 ){ 818 pSublist = sqlite3ExprListAppend(pParse, 0, 819 sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0) 820 ); 821 } 822 823 pSub = sqlite3SelectNew( 824 pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0 825 ); 826 p->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); 827 assert( p->pSrc || db->mallocFailed ); 828 if( p->pSrc ){ 829 p->pSrc->a[0].pSelect = pSub; 830 sqlite3SrcListAssignCursors(pParse, p->pSrc); 831 if( sqlite3ExpandSubquery(pParse, &p->pSrc->a[0]) ){ 832 rc = SQLITE_NOMEM; 833 }else{ 834 pSub->selFlags |= SF_Expanded; 835 p->selFlags &= ~SF_Aggregate; 836 sqlite3SelectPrep(pParse, pSub, 0); 837 } 838 839 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr); 840 }else{ 841 sqlite3SelectDelete(db, pSub); 842 } 843 if( db->mallocFailed ) rc = SQLITE_NOMEM; 844 } 845 846 return rc; 847 } 848 849 /* 850 ** Free the Window object passed as the second argument. 851 */ 852 void sqlite3WindowDelete(sqlite3 *db, Window *p){ 853 if( p ){ 854 sqlite3ExprDelete(db, p->pFilter); 855 sqlite3ExprListDelete(db, p->pPartition); 856 sqlite3ExprListDelete(db, p->pOrderBy); 857 sqlite3ExprDelete(db, p->pEnd); 858 sqlite3ExprDelete(db, p->pStart); 859 sqlite3DbFree(db, p->zName); 860 sqlite3DbFree(db, p); 861 } 862 } 863 864 /* 865 ** Free the linked list of Window objects starting at the second argument. 866 */ 867 void sqlite3WindowListDelete(sqlite3 *db, Window *p){ 868 while( p ){ 869 Window *pNext = p->pNextWin; 870 sqlite3WindowDelete(db, p); 871 p = pNext; 872 } 873 } 874 875 /* 876 ** The argument expression is an PRECEDING or FOLLOWING offset. The 877 ** value should be a non-negative integer. If the value is not a 878 ** constant, change it to NULL. The fact that it is then a non-negative 879 ** integer will be caught later. But it is important not to leave 880 ** variable values in the expression tree. 881 */ 882 static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){ 883 if( 0==sqlite3ExprIsConstant(pExpr) ){ 884 sqlite3ExprDelete(pParse->db, pExpr); 885 pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0); 886 } 887 return pExpr; 888 } 889 890 /* 891 ** Allocate and return a new Window object describing a Window Definition. 892 */ 893 Window *sqlite3WindowAlloc( 894 Parse *pParse, /* Parsing context */ 895 int eType, /* Frame type. TK_RANGE or TK_ROWS */ 896 int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */ 897 Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */ 898 int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */ 899 Expr *pEnd /* End window size if TK_FOLLOWING or PRECEDING */ 900 ){ 901 Window *pWin = 0; 902 903 /* Parser assures the following: */ 904 assert( eType==TK_RANGE || eType==TK_ROWS ); 905 assert( eStart==TK_CURRENT || eStart==TK_PRECEDING 906 || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING ); 907 assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING 908 || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING ); 909 assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) ); 910 assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) ); 911 912 913 /* If a frame is declared "RANGE" (not "ROWS"), then it may not use 914 ** either "<expr> PRECEDING" or "<expr> FOLLOWING". 915 */ 916 if( eType==TK_RANGE && (pStart!=0 || pEnd!=0) ){ 917 sqlite3ErrorMsg(pParse, "RANGE must use only UNBOUNDED or CURRENT ROW"); 918 goto windowAllocErr; 919 } 920 921 /* Additionally, the 922 ** starting boundary type may not occur earlier in the following list than 923 ** the ending boundary type: 924 ** 925 ** UNBOUNDED PRECEDING 926 ** <expr> PRECEDING 927 ** CURRENT ROW 928 ** <expr> FOLLOWING 929 ** UNBOUNDED FOLLOWING 930 ** 931 ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending 932 ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting 933 ** frame boundary. 934 */ 935 if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING) 936 || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT)) 937 ){ 938 sqlite3ErrorMsg(pParse, "unsupported frame delimiter for ROWS"); 939 goto windowAllocErr; 940 } 941 942 pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window)); 943 if( pWin==0 ) goto windowAllocErr; 944 pWin->eType = eType; 945 pWin->eStart = eStart; 946 pWin->eEnd = eEnd; 947 pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd); 948 pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart); 949 return pWin; 950 951 windowAllocErr: 952 sqlite3ExprDelete(pParse->db, pEnd); 953 sqlite3ExprDelete(pParse->db, pStart); 954 return 0; 955 } 956 957 /* 958 ** Attach window object pWin to expression p. 959 */ 960 void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){ 961 if( p ){ 962 if( pWin ){ 963 p->pWin = pWin; 964 pWin->pOwner = p; 965 if( p->flags & EP_Distinct ){ 966 sqlite3ErrorMsg(pParse, 967 "DISTINCT is not supported for window functions"); 968 } 969 } 970 }else{ 971 sqlite3WindowDelete(pParse->db, pWin); 972 } 973 } 974 975 /* 976 ** Return 0 if the two window objects are identical, or non-zero otherwise. 977 ** Identical window objects can be processed in a single scan. 978 */ 979 int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2){ 980 if( p1->eType!=p2->eType ) return 1; 981 if( p1->eStart!=p2->eStart ) return 1; 982 if( p1->eEnd!=p2->eEnd ) return 1; 983 if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1; 984 if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1; 985 if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1; 986 if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1; 987 return 0; 988 } 989 990 991 /* 992 ** This is called by code in select.c before it calls sqlite3WhereBegin() 993 ** to begin iterating through the sub-query results. It is used to allocate 994 ** and initialize registers and cursors used by sqlite3WindowCodeStep(). 995 */ 996 void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){ 997 Window *pWin; 998 Vdbe *v = sqlite3GetVdbe(pParse); 999 int nPart = (pMWin->pPartition ? pMWin->pPartition->nExpr : 0); 1000 nPart += (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0); 1001 if( nPart ){ 1002 pMWin->regPart = pParse->nMem+1; 1003 pParse->nMem += nPart; 1004 sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nPart-1); 1005 } 1006 1007 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1008 FuncDef *p = pWin->pFunc; 1009 if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){ 1010 /* The inline versions of min() and max() require a single ephemeral 1011 ** table and 3 registers. The registers are used as follows: 1012 ** 1013 ** regApp+0: slot to copy min()/max() argument to for MakeRecord 1014 ** regApp+1: integer value used to ensure keys are unique 1015 ** regApp+2: output of MakeRecord 1016 */ 1017 ExprList *pList = pWin->pOwner->x.pList; 1018 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0); 1019 pWin->csrApp = pParse->nTab++; 1020 pWin->regApp = pParse->nMem+1; 1021 pParse->nMem += 3; 1022 if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){ 1023 assert( pKeyInfo->aSortOrder[0]==0 ); 1024 pKeyInfo->aSortOrder[0] = 1; 1025 } 1026 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2); 1027 sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO); 1028 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1); 1029 } 1030 else if( p->zName==nth_valueName || p->zName==first_valueName ){ 1031 /* Allocate two registers at pWin->regApp. These will be used to 1032 ** store the start and end index of the current frame. */ 1033 assert( pMWin->iEphCsr ); 1034 pWin->regApp = pParse->nMem+1; 1035 pWin->csrApp = pParse->nTab++; 1036 pParse->nMem += 2; 1037 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr); 1038 } 1039 else if( p->zName==leadName || p->zName==lagName ){ 1040 assert( pMWin->iEphCsr ); 1041 pWin->csrApp = pParse->nTab++; 1042 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr); 1043 } 1044 } 1045 } 1046 1047 /* 1048 ** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the 1049 ** value of the second argument to nth_value() (eCond==2) has just been 1050 ** evaluated and the result left in register reg. This function generates VM 1051 ** code to check that the value is a non-negative integer and throws an 1052 ** exception if it is not. 1053 */ 1054 static void windowCheckIntValue(Parse *pParse, int reg, int eCond){ 1055 static const char *azErr[] = { 1056 "frame starting offset must be a non-negative integer", 1057 "frame ending offset must be a non-negative integer", 1058 "second argument to nth_value must be a positive integer" 1059 }; 1060 static int aOp[] = { OP_Ge, OP_Ge, OP_Gt }; 1061 Vdbe *v = sqlite3GetVdbe(pParse); 1062 int regZero = sqlite3GetTempReg(pParse); 1063 assert( eCond==0 || eCond==1 || eCond==2 ); 1064 sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero); 1065 sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2); 1066 VdbeCoverageIf(v, eCond==0); 1067 VdbeCoverageIf(v, eCond==1); 1068 VdbeCoverageIf(v, eCond==2); 1069 sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg); 1070 VdbeCoverageNeverNullIf(v, eCond==0); 1071 VdbeCoverageNeverNullIf(v, eCond==1); 1072 VdbeCoverageNeverNullIf(v, eCond==2); 1073 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort); 1074 sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC); 1075 sqlite3ReleaseTempReg(pParse, regZero); 1076 } 1077 1078 /* 1079 ** Return the number of arguments passed to the window-function associated 1080 ** with the object passed as the only argument to this function. 1081 */ 1082 static int windowArgCount(Window *pWin){ 1083 ExprList *pList = pWin->pOwner->x.pList; 1084 return (pList ? pList->nExpr : 0); 1085 } 1086 1087 /* 1088 ** Generate VM code to invoke either xStep() (if bInverse is 0) or 1089 ** xInverse (if bInverse is non-zero) for each window function in the 1090 ** linked list starting at pMWin. Or, for built-in window functions 1091 ** that do not use the standard function API, generate the required 1092 ** inline VM code. 1093 ** 1094 ** If argument csr is greater than or equal to 0, then argument reg is 1095 ** the first register in an array of registers guaranteed to be large 1096 ** enough to hold the array of arguments for each function. In this case 1097 ** the arguments are extracted from the current row of csr into the 1098 ** array of registers before invoking OP_AggStep or OP_AggInverse 1099 ** 1100 ** Or, if csr is less than zero, then the array of registers at reg is 1101 ** already populated with all columns from the current row of the sub-query. 1102 ** 1103 ** If argument regPartSize is non-zero, then it is a register containing the 1104 ** number of rows in the current partition. 1105 */ 1106 static void windowAggStep( 1107 Parse *pParse, 1108 Window *pMWin, /* Linked list of window functions */ 1109 int csr, /* Read arguments from this cursor */ 1110 int bInverse, /* True to invoke xInverse instead of xStep */ 1111 int reg, /* Array of registers */ 1112 int regPartSize /* Register containing size of partition */ 1113 ){ 1114 Vdbe *v = sqlite3GetVdbe(pParse); 1115 Window *pWin; 1116 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1117 int flags = pWin->pFunc->funcFlags; 1118 int regArg; 1119 int nArg = windowArgCount(pWin); 1120 1121 if( csr>=0 ){ 1122 int i; 1123 for(i=0; i<nArg; i++){ 1124 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i); 1125 } 1126 regArg = reg; 1127 if( flags & SQLITE_FUNC_WINDOW_SIZE ){ 1128 if( nArg==0 ){ 1129 regArg = regPartSize; 1130 }else{ 1131 sqlite3VdbeAddOp2(v, OP_SCopy, regPartSize, reg+nArg); 1132 } 1133 nArg++; 1134 } 1135 }else{ 1136 assert( !(flags & SQLITE_FUNC_WINDOW_SIZE) ); 1137 regArg = reg + pWin->iArgCol; 1138 } 1139 1140 if( (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX) 1141 && pWin->eStart!=TK_UNBOUNDED 1142 ){ 1143 int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg); 1144 VdbeCoverage(v); 1145 if( bInverse==0 ){ 1146 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1); 1147 sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp); 1148 sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2); 1149 sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2); 1150 }else{ 1151 sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1); 1152 VdbeCoverageNeverTaken(v); 1153 sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp); 1154 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); 1155 } 1156 sqlite3VdbeJumpHere(v, addrIsNull); 1157 }else if( pWin->regApp ){ 1158 assert( pWin->pFunc->zName==nth_valueName 1159 || pWin->pFunc->zName==first_valueName 1160 ); 1161 assert( bInverse==0 || bInverse==1 ); 1162 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1); 1163 }else if( pWin->pFunc->zName==leadName 1164 || pWin->pFunc->zName==lagName 1165 ){ 1166 /* no-op */ 1167 }else{ 1168 int addrIf = 0; 1169 if( pWin->pFilter ){ 1170 int regTmp; 1171 assert( nArg==0 || nArg==pWin->pOwner->x.pList->nExpr ); 1172 assert( nArg || pWin->pOwner->x.pList==0 ); 1173 if( csr>0 ){ 1174 regTmp = sqlite3GetTempReg(pParse); 1175 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp); 1176 }else{ 1177 regTmp = regArg + nArg; 1178 } 1179 addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1); 1180 VdbeCoverage(v); 1181 if( csr>0 ){ 1182 sqlite3ReleaseTempReg(pParse, regTmp); 1183 } 1184 } 1185 if( pWin->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ 1186 CollSeq *pColl; 1187 assert( nArg>0 ); 1188 pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr); 1189 sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ); 1190 } 1191 sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep, 1192 bInverse, regArg, pWin->regAccum); 1193 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF); 1194 sqlite3VdbeChangeP5(v, (u8)nArg); 1195 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf); 1196 } 1197 } 1198 } 1199 1200 /* 1201 ** Generate VM code to invoke either xValue() (bFinal==0) or xFinalize() 1202 ** (bFinal==1) for each window function in the linked list starting at 1203 ** pMWin. Or, for built-in window-functions that do not use the standard 1204 ** API, generate the equivalent VM code. 1205 */ 1206 static void windowAggFinal(Parse *pParse, Window *pMWin, int bFinal){ 1207 Vdbe *v = sqlite3GetVdbe(pParse); 1208 Window *pWin; 1209 1210 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1211 if( (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX) 1212 && pWin->eStart!=TK_UNBOUNDED 1213 ){ 1214 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult); 1215 sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp); 1216 VdbeCoverage(v); 1217 sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult); 1218 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); 1219 if( bFinal ){ 1220 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp); 1221 } 1222 }else if( pWin->regApp ){ 1223 }else{ 1224 if( bFinal ){ 1225 sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, windowArgCount(pWin)); 1226 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF); 1227 sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult); 1228 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); 1229 }else{ 1230 sqlite3VdbeAddOp3(v, OP_AggValue, pWin->regAccum, windowArgCount(pWin), 1231 pWin->regResult); 1232 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF); 1233 } 1234 } 1235 } 1236 } 1237 1238 /* 1239 ** This function generates VM code to invoke the sub-routine at address 1240 ** lblFlushPart once for each partition with the entire partition cached in 1241 ** the Window.iEphCsr temp table. 1242 */ 1243 static void windowPartitionCache( 1244 Parse *pParse, 1245 Select *p, /* The rewritten SELECT statement */ 1246 WhereInfo *pWInfo, /* WhereInfo to call WhereEnd() on */ 1247 int regFlushPart, /* Register to use with Gosub lblFlushPart */ 1248 int lblFlushPart, /* Subroutine to Gosub to */ 1249 int *pRegSize /* OUT: Register containing partition size */ 1250 ){ 1251 Window *pMWin = p->pWin; 1252 Vdbe *v = sqlite3GetVdbe(pParse); 1253 int iSubCsr = p->pSrc->a[0].iCursor; 1254 int nSub = p->pSrc->a[0].pTab->nCol; 1255 int k; 1256 1257 int reg = pParse->nMem+1; 1258 int regRecord = reg+nSub; 1259 int regRowid = regRecord+1; 1260 1261 *pRegSize = regRowid; 1262 pParse->nMem += nSub + 2; 1263 1264 /* Load the column values for the row returned by the sub-select 1265 ** into an array of registers starting at reg. */ 1266 for(k=0; k<nSub; k++){ 1267 sqlite3VdbeAddOp3(v, OP_Column, iSubCsr, k, reg+k); 1268 } 1269 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg, nSub, regRecord); 1270 1271 /* Check if this is the start of a new partition. If so, call the 1272 ** flush_partition sub-routine. */ 1273 if( pMWin->pPartition ){ 1274 int addr; 1275 ExprList *pPart = pMWin->pPartition; 1276 int nPart = pPart->nExpr; 1277 int regNewPart = reg + pMWin->nBufferCol; 1278 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0); 1279 1280 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart,nPart); 1281 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO); 1282 sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2); 1283 VdbeCoverageEqNe(v); 1284 sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1); 1285 sqlite3VdbeAddOp2(v, OP_Gosub, regFlushPart, lblFlushPart); 1286 VdbeComment((v, "call flush_partition")); 1287 } 1288 1289 /* Buffer the current row in the ephemeral table. */ 1290 sqlite3VdbeAddOp2(v, OP_NewRowid, pMWin->iEphCsr, regRowid); 1291 sqlite3VdbeAddOp3(v, OP_Insert, pMWin->iEphCsr, regRecord, regRowid); 1292 1293 /* End of the input loop */ 1294 sqlite3WhereEnd(pWInfo); 1295 1296 /* Invoke "flush_partition" to deal with the final (or only) partition */ 1297 sqlite3VdbeAddOp2(v, OP_Gosub, regFlushPart, lblFlushPart); 1298 VdbeComment((v, "call flush_partition")); 1299 } 1300 1301 /* 1302 ** Invoke the sub-routine at regGosub (generated by code in select.c) to 1303 ** return the current row of Window.iEphCsr. If all window functions are 1304 ** aggregate window functions that use the standard API, a single 1305 ** OP_Gosub instruction is all that this routine generates. Extra VM code 1306 ** for per-row processing is only generated for the following built-in window 1307 ** functions: 1308 ** 1309 ** nth_value() 1310 ** first_value() 1311 ** lag() 1312 ** lead() 1313 */ 1314 static void windowReturnOneRow( 1315 Parse *pParse, 1316 Window *pMWin, 1317 int regGosub, 1318 int addrGosub 1319 ){ 1320 Vdbe *v = sqlite3GetVdbe(pParse); 1321 Window *pWin; 1322 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1323 FuncDef *pFunc = pWin->pFunc; 1324 if( pFunc->zName==nth_valueName 1325 || pFunc->zName==first_valueName 1326 ){ 1327 int csr = pWin->csrApp; 1328 int lbl = sqlite3VdbeMakeLabel(v); 1329 int tmpReg = sqlite3GetTempReg(pParse); 1330 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult); 1331 1332 if( pFunc->zName==nth_valueName ){ 1333 sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+1,tmpReg); 1334 windowCheckIntValue(pParse, tmpReg, 2); 1335 }else{ 1336 sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg); 1337 } 1338 sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg); 1339 sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg); 1340 VdbeCoverageNeverNull(v); 1341 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg); 1342 VdbeCoverageNeverTaken(v); 1343 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult); 1344 sqlite3VdbeResolveLabel(v, lbl); 1345 sqlite3ReleaseTempReg(pParse, tmpReg); 1346 } 1347 else if( pFunc->zName==leadName || pFunc->zName==lagName ){ 1348 int nArg = pWin->pOwner->x.pList->nExpr; 1349 int iEph = pMWin->iEphCsr; 1350 int csr = pWin->csrApp; 1351 int lbl = sqlite3VdbeMakeLabel(v); 1352 int tmpReg = sqlite3GetTempReg(pParse); 1353 1354 if( nArg<3 ){ 1355 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult); 1356 }else{ 1357 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+2, pWin->regResult); 1358 } 1359 sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg); 1360 if( nArg<2 ){ 1361 int val = (pFunc->zName==leadName ? 1 : -1); 1362 sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val); 1363 }else{ 1364 int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract); 1365 int tmpReg2 = sqlite3GetTempReg(pParse); 1366 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2); 1367 sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg); 1368 sqlite3ReleaseTempReg(pParse, tmpReg2); 1369 } 1370 1371 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg); 1372 VdbeCoverage(v); 1373 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult); 1374 sqlite3VdbeResolveLabel(v, lbl); 1375 sqlite3ReleaseTempReg(pParse, tmpReg); 1376 } 1377 } 1378 sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub); 1379 } 1380 1381 /* 1382 ** Invoke the code generated by windowReturnOneRow() and, optionally, the 1383 ** xInverse() function for each window function, for one or more rows 1384 ** from the Window.iEphCsr temp table. This routine generates VM code 1385 ** similar to: 1386 ** 1387 ** while( regCtr>0 ){ 1388 ** regCtr--; 1389 ** windowReturnOneRow() 1390 ** if( bInverse ){ 1391 ** AggInverse 1392 ** } 1393 ** Next (Window.iEphCsr) 1394 ** } 1395 */ 1396 static void windowReturnRows( 1397 Parse *pParse, 1398 Window *pMWin, /* List of window functions */ 1399 int regCtr, /* Register containing number of rows */ 1400 int regGosub, /* Register for Gosub addrGosub */ 1401 int addrGosub, /* Address of sub-routine for ReturnOneRow */ 1402 int regInvArg, /* Array of registers for xInverse args */ 1403 int regInvSize /* Register containing size of partition */ 1404 ){ 1405 int addr; 1406 Vdbe *v = sqlite3GetVdbe(pParse); 1407 windowAggFinal(pParse, pMWin, 0); 1408 addr = sqlite3VdbeAddOp3(v, OP_IfPos, regCtr, sqlite3VdbeCurrentAddr(v)+2 ,1); 1409 VdbeCoverage(v); 1410 sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); 1411 windowReturnOneRow(pParse, pMWin, regGosub, addrGosub); 1412 if( regInvArg ){ 1413 windowAggStep(pParse, pMWin, pMWin->iEphCsr, 1, regInvArg, regInvSize); 1414 } 1415 sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, addr); 1416 VdbeCoverage(v); 1417 sqlite3VdbeJumpHere(v, addr+1); /* The OP_Goto */ 1418 } 1419 1420 /* 1421 ** Generate code to set the accumulator register for each window function 1422 ** in the linked list passed as the second argument to NULL. And perform 1423 ** any equivalent initialization required by any built-in window functions 1424 ** in the list. 1425 */ 1426 static int windowInitAccum(Parse *pParse, Window *pMWin){ 1427 Vdbe *v = sqlite3GetVdbe(pParse); 1428 int regArg; 1429 int nArg = 0; 1430 Window *pWin; 1431 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1432 FuncDef *pFunc = pWin->pFunc; 1433 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); 1434 nArg = MAX(nArg, windowArgCount(pWin)); 1435 if( pFunc->zName==nth_valueName 1436 || pFunc->zName==first_valueName 1437 ){ 1438 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp); 1439 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1); 1440 } 1441 1442 if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){ 1443 assert( pWin->eStart!=TK_UNBOUNDED ); 1444 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp); 1445 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1); 1446 } 1447 } 1448 regArg = pParse->nMem+1; 1449 pParse->nMem += nArg; 1450 return regArg; 1451 } 1452 1453 1454 /* 1455 ** This function does the work of sqlite3WindowCodeStep() for all "ROWS" 1456 ** window frame types except for "BETWEEN UNBOUNDED PRECEDING AND CURRENT 1457 ** ROW". Pseudo-code for each follows. 1458 ** 1459 ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING 1460 ** 1461 ** ... 1462 ** if( new partition ){ 1463 ** Gosub flush_partition 1464 ** } 1465 ** Insert (record in eph-table) 1466 ** sqlite3WhereEnd() 1467 ** Gosub flush_partition 1468 ** 1469 ** flush_partition: 1470 ** Once { 1471 ** OpenDup (iEphCsr -> csrStart) 1472 ** OpenDup (iEphCsr -> csrEnd) 1473 ** } 1474 ** regStart = <expr1> // PRECEDING expression 1475 ** regEnd = <expr2> // FOLLOWING expression 1476 ** if( regStart<0 || regEnd<0 ){ error! } 1477 ** Rewind (csr,csrStart,csrEnd) // if EOF goto flush_partition_done 1478 ** Next(csrEnd) // if EOF skip Aggstep 1479 ** Aggstep (csrEnd) 1480 ** if( (regEnd--)<=0 ){ 1481 ** AggFinal (xValue) 1482 ** Gosub addrGosub 1483 ** Next(csr) // if EOF goto flush_partition_done 1484 ** if( (regStart--)<=0 ){ 1485 ** AggInverse (csrStart) 1486 ** Next(csrStart) 1487 ** } 1488 ** } 1489 ** flush_partition_done: 1490 ** ResetSorter (csr) 1491 ** Return 1492 ** 1493 ** ROWS BETWEEN <expr> PRECEDING AND CURRENT ROW 1494 ** ROWS BETWEEN CURRENT ROW AND <expr> FOLLOWING 1495 ** ROWS BETWEEN UNBOUNDED PRECEDING AND <expr> FOLLOWING 1496 ** 1497 ** These are similar to the above. For "CURRENT ROW", intialize the 1498 ** register to 0. For "UNBOUNDED PRECEDING" to infinity. 1499 ** 1500 ** ROWS BETWEEN <expr> PRECEDING AND UNBOUNDED FOLLOWING 1501 ** ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING 1502 ** 1503 ** Rewind (csr,csrStart,csrEnd) // if EOF goto flush_partition_done 1504 ** while( 1 ){ 1505 ** Next(csrEnd) // Exit while(1) at EOF 1506 ** Aggstep (csrEnd) 1507 ** } 1508 ** while( 1 ){ 1509 ** AggFinal (xValue) 1510 ** Gosub addrGosub 1511 ** Next(csr) // if EOF goto flush_partition_done 1512 ** if( (regStart--)<=0 ){ 1513 ** AggInverse (csrStart) 1514 ** Next(csrStart) 1515 ** } 1516 ** } 1517 ** 1518 ** For the "CURRENT ROW AND UNBOUNDED FOLLOWING" case, the final if() 1519 ** condition is always true (as if regStart were initialized to 0). 1520 ** 1521 ** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING 1522 ** 1523 ** This is the only RANGE case handled by this routine. It modifies the 1524 ** second while( 1 ) loop in "ROWS BETWEEN CURRENT ... UNBOUNDED..." to 1525 ** be: 1526 ** 1527 ** while( 1 ){ 1528 ** AggFinal (xValue) 1529 ** while( 1 ){ 1530 ** regPeer++ 1531 ** Gosub addrGosub 1532 ** Next(csr) // if EOF goto flush_partition_done 1533 ** if( new peer ) break; 1534 ** } 1535 ** while( (regPeer--)>0 ){ 1536 ** AggInverse (csrStart) 1537 ** Next(csrStart) 1538 ** } 1539 ** } 1540 ** 1541 ** ROWS BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING 1542 ** 1543 ** regEnd = regEnd - regStart 1544 ** Rewind (csr,csrStart,csrEnd) // if EOF goto flush_partition_done 1545 ** Aggstep (csrEnd) 1546 ** Next(csrEnd) // if EOF fall-through 1547 ** if( (regEnd--)<=0 ){ 1548 ** if( (regStart--)<=0 ){ 1549 ** AggFinal (xValue) 1550 ** Gosub addrGosub 1551 ** Next(csr) // if EOF goto flush_partition_done 1552 ** } 1553 ** AggInverse (csrStart) 1554 ** Next (csrStart) 1555 ** } 1556 ** 1557 ** ROWS BETWEEN <expr> PRECEDING AND <expr> PRECEDING 1558 ** 1559 ** Replace the bit after "Rewind" in the above with: 1560 ** 1561 ** if( (regEnd--)<=0 ){ 1562 ** AggStep (csrEnd) 1563 ** Next (csrEnd) 1564 ** } 1565 ** AggFinal (xValue) 1566 ** Gosub addrGosub 1567 ** Next(csr) // if EOF goto flush_partition_done 1568 ** if( (regStart--)<=0 ){ 1569 ** AggInverse (csr2) 1570 ** Next (csr2) 1571 ** } 1572 ** 1573 */ 1574 static void windowCodeRowExprStep( 1575 Parse *pParse, 1576 Select *p, 1577 WhereInfo *pWInfo, 1578 int regGosub, 1579 int addrGosub 1580 ){ 1581 Window *pMWin = p->pWin; 1582 Vdbe *v = sqlite3GetVdbe(pParse); 1583 int regFlushPart; /* Register for "Gosub flush_partition" */ 1584 int lblFlushPart; /* Label for "Gosub flush_partition" */ 1585 int lblFlushDone; /* Label for "Gosub flush_partition_done" */ 1586 1587 int regArg; 1588 int addr; 1589 int csrStart = pParse->nTab++; 1590 int csrEnd = pParse->nTab++; 1591 int regStart; /* Value of <expr> PRECEDING */ 1592 int regEnd; /* Value of <expr> FOLLOWING */ 1593 int addrGoto; 1594 int addrTop; 1595 int addrIfPos1 = 0; 1596 int addrIfPos2 = 0; 1597 int regSize = 0; 1598 1599 assert( pMWin->eStart==TK_PRECEDING 1600 || pMWin->eStart==TK_CURRENT 1601 || pMWin->eStart==TK_FOLLOWING 1602 || pMWin->eStart==TK_UNBOUNDED 1603 ); 1604 assert( pMWin->eEnd==TK_FOLLOWING 1605 || pMWin->eEnd==TK_CURRENT 1606 || pMWin->eEnd==TK_UNBOUNDED 1607 || pMWin->eEnd==TK_PRECEDING 1608 ); 1609 1610 /* Allocate register and label for the "flush_partition" sub-routine. */ 1611 regFlushPart = ++pParse->nMem; 1612 lblFlushPart = sqlite3VdbeMakeLabel(v); 1613 lblFlushDone = sqlite3VdbeMakeLabel(v); 1614 1615 regStart = ++pParse->nMem; 1616 regEnd = ++pParse->nMem; 1617 1618 windowPartitionCache(pParse, p, pWInfo, regFlushPart, lblFlushPart, ®Size); 1619 1620 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto); 1621 1622 /* Start of "flush_partition" */ 1623 sqlite3VdbeResolveLabel(v, lblFlushPart); 1624 sqlite3VdbeAddOp2(v, OP_Once, 0, sqlite3VdbeCurrentAddr(v)+3); 1625 VdbeCoverage(v); 1626 VdbeComment((v, "Flush_partition subroutine")); 1627 sqlite3VdbeAddOp2(v, OP_OpenDup, csrStart, pMWin->iEphCsr); 1628 sqlite3VdbeAddOp2(v, OP_OpenDup, csrEnd, pMWin->iEphCsr); 1629 1630 /* If either regStart or regEnd are not non-negative integers, throw 1631 ** an exception. */ 1632 if( pMWin->pStart ){ 1633 sqlite3ExprCode(pParse, pMWin->pStart, regStart); 1634 windowCheckIntValue(pParse, regStart, 0); 1635 } 1636 if( pMWin->pEnd ){ 1637 sqlite3ExprCode(pParse, pMWin->pEnd, regEnd); 1638 windowCheckIntValue(pParse, regEnd, 1); 1639 } 1640 1641 /* If this is "ROWS <expr1> FOLLOWING AND ROWS <expr2> FOLLOWING", do: 1642 ** 1643 ** if( regEnd<regStart ){ 1644 ** // The frame always consists of 0 rows 1645 ** regStart = regSize; 1646 ** } 1647 ** regEnd = regEnd - regStart; 1648 */ 1649 if( pMWin->pEnd && pMWin->eStart==TK_FOLLOWING ){ 1650 assert( pMWin->pStart!=0 ); 1651 assert( pMWin->eEnd==TK_FOLLOWING ); 1652 sqlite3VdbeAddOp3(v, OP_Ge, regStart, sqlite3VdbeCurrentAddr(v)+2, regEnd); 1653 VdbeCoverageNeverNull(v); 1654 sqlite3VdbeAddOp2(v, OP_Copy, regSize, regStart); 1655 sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regEnd); 1656 } 1657 1658 if( pMWin->pStart && pMWin->eEnd==TK_PRECEDING ){ 1659 assert( pMWin->pEnd!=0 ); 1660 assert( pMWin->eStart==TK_PRECEDING ); 1661 sqlite3VdbeAddOp3(v, OP_Le, regStart, sqlite3VdbeCurrentAddr(v)+3, regEnd); 1662 VdbeCoverageNeverNull(v); 1663 sqlite3VdbeAddOp2(v, OP_Copy, regSize, regStart); 1664 sqlite3VdbeAddOp2(v, OP_Copy, regSize, regEnd); 1665 } 1666 1667 /* Initialize the accumulator register for each window function to NULL */ 1668 regArg = windowInitAccum(pParse, pMWin); 1669 1670 sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr, lblFlushDone); 1671 VdbeCoverage(v); 1672 sqlite3VdbeAddOp2(v, OP_Rewind, csrStart, lblFlushDone); 1673 VdbeCoverageNeverTaken(v); 1674 sqlite3VdbeChangeP5(v, 1); 1675 sqlite3VdbeAddOp2(v, OP_Rewind, csrEnd, lblFlushDone); 1676 VdbeCoverageNeverTaken(v); 1677 sqlite3VdbeChangeP5(v, 1); 1678 1679 /* Invoke AggStep function for each window function using the row that 1680 ** csrEnd currently points to. Or, if csrEnd is already at EOF, 1681 ** do nothing. */ 1682 addrTop = sqlite3VdbeCurrentAddr(v); 1683 if( pMWin->eEnd==TK_PRECEDING ){ 1684 addrIfPos1 = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0 , 1); 1685 VdbeCoverage(v); 1686 } 1687 sqlite3VdbeAddOp2(v, OP_Next, csrEnd, sqlite3VdbeCurrentAddr(v)+2); 1688 VdbeCoverage(v); 1689 addr = sqlite3VdbeAddOp0(v, OP_Goto); 1690 windowAggStep(pParse, pMWin, csrEnd, 0, regArg, regSize); 1691 if( pMWin->eEnd==TK_UNBOUNDED ){ 1692 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop); 1693 sqlite3VdbeJumpHere(v, addr); 1694 addrTop = sqlite3VdbeCurrentAddr(v); 1695 }else{ 1696 sqlite3VdbeJumpHere(v, addr); 1697 if( pMWin->eEnd==TK_PRECEDING ){ 1698 sqlite3VdbeJumpHere(v, addrIfPos1); 1699 } 1700 } 1701 1702 if( pMWin->eEnd==TK_FOLLOWING ){ 1703 addrIfPos1 = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0 , 1); 1704 VdbeCoverage(v); 1705 } 1706 if( pMWin->eStart==TK_FOLLOWING ){ 1707 addrIfPos2 = sqlite3VdbeAddOp3(v, OP_IfPos, regStart, 0 , 1); 1708 VdbeCoverage(v); 1709 } 1710 windowAggFinal(pParse, pMWin, 0); 1711 windowReturnOneRow(pParse, pMWin, regGosub, addrGosub); 1712 sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)+2); 1713 VdbeCoverage(v); 1714 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblFlushDone); 1715 if( pMWin->eStart==TK_FOLLOWING ){ 1716 sqlite3VdbeJumpHere(v, addrIfPos2); 1717 } 1718 1719 if( pMWin->eStart==TK_CURRENT 1720 || pMWin->eStart==TK_PRECEDING 1721 || pMWin->eStart==TK_FOLLOWING 1722 ){ 1723 int lblSkipInverse = sqlite3VdbeMakeLabel(v);; 1724 if( pMWin->eStart==TK_PRECEDING ){ 1725 sqlite3VdbeAddOp3(v, OP_IfPos, regStart, lblSkipInverse, 1); 1726 VdbeCoverage(v); 1727 } 1728 if( pMWin->eStart==TK_FOLLOWING ){ 1729 sqlite3VdbeAddOp2(v, OP_Next, csrStart, sqlite3VdbeCurrentAddr(v)+2); 1730 VdbeCoverage(v); 1731 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblSkipInverse); 1732 }else{ 1733 sqlite3VdbeAddOp2(v, OP_Next, csrStart, sqlite3VdbeCurrentAddr(v)+1); 1734 VdbeCoverageAlwaysTaken(v); 1735 } 1736 windowAggStep(pParse, pMWin, csrStart, 1, regArg, regSize); 1737 sqlite3VdbeResolveLabel(v, lblSkipInverse); 1738 } 1739 if( pMWin->eEnd==TK_FOLLOWING ){ 1740 sqlite3VdbeJumpHere(v, addrIfPos1); 1741 } 1742 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop); 1743 1744 /* flush_partition_done: */ 1745 sqlite3VdbeResolveLabel(v, lblFlushDone); 1746 sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr); 1747 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart); 1748 VdbeComment((v, "end flush_partition subroutine")); 1749 1750 /* Jump to here to skip over flush_partition */ 1751 sqlite3VdbeJumpHere(v, addrGoto); 1752 } 1753 1754 /* 1755 ** This function does the work of sqlite3WindowCodeStep() for cases that 1756 ** would normally be handled by windowCodeDefaultStep() when there are 1757 ** one or more built-in window-functions that require the entire partition 1758 ** to be cached in a temp table before any rows can be returned. Additionally. 1759 ** "RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING" is always handled by 1760 ** this function. 1761 ** 1762 ** Pseudo-code corresponding to the VM code generated by this function 1763 ** for each type of window follows. 1764 ** 1765 ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 1766 ** 1767 ** flush_partition: 1768 ** Once { 1769 ** OpenDup (iEphCsr -> csrLead) 1770 ** } 1771 ** Integer ctr 0 1772 ** foreach row (csrLead){ 1773 ** if( new peer ){ 1774 ** AggFinal (xValue) 1775 ** for(i=0; i<ctr; i++){ 1776 ** Gosub addrGosub 1777 ** Next iEphCsr 1778 ** } 1779 ** Integer ctr 0 1780 ** } 1781 ** AggStep (csrLead) 1782 ** Incr ctr 1783 ** } 1784 ** 1785 ** AggFinal (xFinalize) 1786 ** for(i=0; i<ctr; i++){ 1787 ** Gosub addrGosub 1788 ** Next iEphCsr 1789 ** } 1790 ** 1791 ** ResetSorter (csr) 1792 ** Return 1793 ** 1794 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 1795 ** 1796 ** As above, except that the "if( new peer )" branch is always taken. 1797 ** 1798 ** RANGE BETWEEN CURRENT ROW AND CURRENT ROW 1799 ** 1800 ** As above, except that each of the for() loops becomes: 1801 ** 1802 ** for(i=0; i<ctr; i++){ 1803 ** Gosub addrGosub 1804 ** AggInverse (iEphCsr) 1805 ** Next iEphCsr 1806 ** } 1807 ** 1808 ** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING 1809 ** 1810 ** flush_partition: 1811 ** Once { 1812 ** OpenDup (iEphCsr -> csrLead) 1813 ** } 1814 ** foreach row (csrLead) { 1815 ** AggStep (csrLead) 1816 ** } 1817 ** foreach row (iEphCsr) { 1818 ** Gosub addrGosub 1819 ** } 1820 ** 1821 ** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING 1822 ** 1823 ** flush_partition: 1824 ** Once { 1825 ** OpenDup (iEphCsr -> csrLead) 1826 ** } 1827 ** foreach row (csrLead){ 1828 ** AggStep (csrLead) 1829 ** } 1830 ** Rewind (csrLead) 1831 ** Integer ctr 0 1832 ** foreach row (csrLead){ 1833 ** if( new peer ){ 1834 ** AggFinal (xValue) 1835 ** for(i=0; i<ctr; i++){ 1836 ** Gosub addrGosub 1837 ** AggInverse (iEphCsr) 1838 ** Next iEphCsr 1839 ** } 1840 ** Integer ctr 0 1841 ** } 1842 ** Incr ctr 1843 ** } 1844 ** 1845 ** AggFinal (xFinalize) 1846 ** for(i=0; i<ctr; i++){ 1847 ** Gosub addrGosub 1848 ** Next iEphCsr 1849 ** } 1850 ** 1851 ** ResetSorter (csr) 1852 ** Return 1853 */ 1854 static void windowCodeCacheStep( 1855 Parse *pParse, 1856 Select *p, 1857 WhereInfo *pWInfo, 1858 int regGosub, 1859 int addrGosub 1860 ){ 1861 Window *pMWin = p->pWin; 1862 Vdbe *v = sqlite3GetVdbe(pParse); 1863 int k; 1864 int addr; 1865 ExprList *pPart = pMWin->pPartition; 1866 ExprList *pOrderBy = pMWin->pOrderBy; 1867 int nPeer = pOrderBy ? pOrderBy->nExpr : 0; 1868 int regNewPeer; 1869 1870 int addrGoto; /* Address of Goto used to jump flush_par.. */ 1871 int addrNext; /* Jump here for next iteration of loop */ 1872 int regFlushPart; 1873 int lblFlushPart; 1874 int csrLead; 1875 int regCtr; 1876 int regArg; /* Register array to martial function args */ 1877 int regSize; 1878 int lblEmpty; 1879 int bReverse = pMWin->pOrderBy && pMWin->eStart==TK_CURRENT 1880 && pMWin->eEnd==TK_UNBOUNDED; 1881 1882 assert( (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT) 1883 || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_UNBOUNDED) 1884 || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_CURRENT) 1885 || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED) 1886 ); 1887 1888 lblEmpty = sqlite3VdbeMakeLabel(v); 1889 regNewPeer = pParse->nMem+1; 1890 pParse->nMem += nPeer; 1891 1892 /* Allocate register and label for the "flush_partition" sub-routine. */ 1893 regFlushPart = ++pParse->nMem; 1894 lblFlushPart = sqlite3VdbeMakeLabel(v); 1895 1896 csrLead = pParse->nTab++; 1897 regCtr = ++pParse->nMem; 1898 1899 windowPartitionCache(pParse, p, pWInfo, regFlushPart, lblFlushPart, ®Size); 1900 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto); 1901 1902 /* Start of "flush_partition" */ 1903 sqlite3VdbeResolveLabel(v, lblFlushPart); 1904 sqlite3VdbeAddOp2(v, OP_Once, 0, sqlite3VdbeCurrentAddr(v)+2); 1905 VdbeCoverage(v); 1906 sqlite3VdbeAddOp2(v, OP_OpenDup, csrLead, pMWin->iEphCsr); 1907 1908 /* Initialize the accumulator register for each window function to NULL */ 1909 regArg = windowInitAccum(pParse, pMWin); 1910 1911 sqlite3VdbeAddOp2(v, OP_Integer, 0, regCtr); 1912 sqlite3VdbeAddOp2(v, OP_Rewind, csrLead, lblEmpty); 1913 VdbeCoverage(v); 1914 sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr, lblEmpty); 1915 VdbeCoverageNeverTaken(v); 1916 1917 if( bReverse ){ 1918 int addr2 = sqlite3VdbeCurrentAddr(v); 1919 windowAggStep(pParse, pMWin, csrLead, 0, regArg, regSize); 1920 sqlite3VdbeAddOp2(v, OP_Next, csrLead, addr2); 1921 VdbeCoverage(v); 1922 sqlite3VdbeAddOp2(v, OP_Rewind, csrLead, lblEmpty); 1923 VdbeCoverageNeverTaken(v); 1924 } 1925 addrNext = sqlite3VdbeCurrentAddr(v); 1926 1927 if( pOrderBy && (pMWin->eEnd==TK_CURRENT || pMWin->eStart==TK_CURRENT) ){ 1928 int bCurrent = (pMWin->eStart==TK_CURRENT); 1929 int addrJump = 0; /* Address of OP_Jump below */ 1930 if( pMWin->eType==TK_RANGE ){ 1931 int iOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0); 1932 int regPeer = pMWin->regPart + (pPart ? pPart->nExpr : 0); 1933 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0); 1934 for(k=0; k<nPeer; k++){ 1935 sqlite3VdbeAddOp3(v, OP_Column, csrLead, iOff+k, regNewPeer+k); 1936 } 1937 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPeer, regPeer, nPeer); 1938 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO); 1939 addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2); 1940 VdbeCoverage(v); 1941 sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, nPeer-1); 1942 } 1943 1944 windowReturnRows(pParse, pMWin, regCtr, regGosub, addrGosub, 1945 (bCurrent ? regArg : 0), (bCurrent ? regSize : 0) 1946 ); 1947 if( addrJump ) sqlite3VdbeJumpHere(v, addrJump); 1948 } 1949 1950 if( bReverse==0 ){ 1951 windowAggStep(pParse, pMWin, csrLead, 0, regArg, regSize); 1952 } 1953 sqlite3VdbeAddOp2(v, OP_AddImm, regCtr, 1); 1954 sqlite3VdbeAddOp2(v, OP_Next, csrLead, addrNext); 1955 VdbeCoverage(v); 1956 1957 windowReturnRows(pParse, pMWin, regCtr, regGosub, addrGosub, 0, 0); 1958 1959 sqlite3VdbeResolveLabel(v, lblEmpty); 1960 sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr); 1961 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart); 1962 1963 /* Jump to here to skip over flush_partition */ 1964 sqlite3VdbeJumpHere(v, addrGoto); 1965 } 1966 1967 1968 /* 1969 ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 1970 ** 1971 ** ... 1972 ** if( new partition ){ 1973 ** AggFinal (xFinalize) 1974 ** Gosub addrGosub 1975 ** ResetSorter eph-table 1976 ** } 1977 ** else if( new peer ){ 1978 ** AggFinal (xValue) 1979 ** Gosub addrGosub 1980 ** ResetSorter eph-table 1981 ** } 1982 ** AggStep 1983 ** Insert (record into eph-table) 1984 ** sqlite3WhereEnd() 1985 ** AggFinal (xFinalize) 1986 ** Gosub addrGosub 1987 ** 1988 ** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING 1989 ** 1990 ** As above, except take no action for a "new peer". Invoke 1991 ** the sub-routine once only for each partition. 1992 ** 1993 ** RANGE BETWEEN CURRENT ROW AND CURRENT ROW 1994 ** 1995 ** As above, except that the "new peer" condition is handled in the 1996 ** same way as "new partition" (so there is no "else if" block). 1997 ** 1998 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 1999 ** 2000 ** As above, except assume every row is a "new peer". 2001 */ 2002 static void windowCodeDefaultStep( 2003 Parse *pParse, 2004 Select *p, 2005 WhereInfo *pWInfo, 2006 int regGosub, 2007 int addrGosub 2008 ){ 2009 Window *pMWin = p->pWin; 2010 Vdbe *v = sqlite3GetVdbe(pParse); 2011 int k; 2012 int iSubCsr = p->pSrc->a[0].iCursor; 2013 int nSub = p->pSrc->a[0].pTab->nCol; 2014 int reg = pParse->nMem+1; 2015 int regRecord = reg+nSub; 2016 int regRowid = regRecord+1; 2017 int addr; 2018 ExprList *pPart = pMWin->pPartition; 2019 ExprList *pOrderBy = pMWin->pOrderBy; 2020 2021 assert( pMWin->eType==TK_RANGE 2022 || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT) 2023 ); 2024 2025 assert( (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT) 2026 || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_UNBOUNDED) 2027 || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_CURRENT) 2028 || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED && !pOrderBy) 2029 ); 2030 2031 if( pMWin->eEnd==TK_UNBOUNDED ){ 2032 pOrderBy = 0; 2033 } 2034 2035 pParse->nMem += nSub + 2; 2036 2037 /* Load the individual column values of the row returned by 2038 ** the sub-select into an array of registers. */ 2039 for(k=0; k<nSub; k++){ 2040 sqlite3VdbeAddOp3(v, OP_Column, iSubCsr, k, reg+k); 2041 } 2042 2043 /* Check if this is the start of a new partition or peer group. */ 2044 if( pPart || pOrderBy ){ 2045 int nPart = (pPart ? pPart->nExpr : 0); 2046 int addrGoto = 0; 2047 int addrJump = 0; 2048 int nPeer = (pOrderBy ? pOrderBy->nExpr : 0); 2049 2050 if( pPart ){ 2051 int regNewPart = reg + pMWin->nBufferCol; 2052 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0); 2053 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart,nPart); 2054 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO); 2055 addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2); 2056 VdbeCoverageEqNe(v); 2057 windowAggFinal(pParse, pMWin, 1); 2058 if( pOrderBy ){ 2059 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto); 2060 } 2061 } 2062 2063 if( pOrderBy ){ 2064 int regNewPeer = reg + pMWin->nBufferCol + nPart; 2065 int regPeer = pMWin->regPart + nPart; 2066 2067 if( addrJump ) sqlite3VdbeJumpHere(v, addrJump); 2068 if( pMWin->eType==TK_RANGE ){ 2069 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0); 2070 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPeer, regPeer, nPeer); 2071 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO); 2072 addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2); 2073 VdbeCoverage(v); 2074 }else{ 2075 addrJump = 0; 2076 } 2077 windowAggFinal(pParse, pMWin, pMWin->eStart==TK_CURRENT); 2078 if( addrGoto ) sqlite3VdbeJumpHere(v, addrGoto); 2079 } 2080 2081 sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr,sqlite3VdbeCurrentAddr(v)+3); 2082 VdbeCoverage(v); 2083 sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub); 2084 sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)-1); 2085 VdbeCoverage(v); 2086 2087 sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr); 2088 sqlite3VdbeAddOp3( 2089 v, OP_Copy, reg+pMWin->nBufferCol, pMWin->regPart, nPart+nPeer-1 2090 ); 2091 2092 if( addrJump ) sqlite3VdbeJumpHere(v, addrJump); 2093 } 2094 2095 /* Invoke step function for window functions */ 2096 windowAggStep(pParse, pMWin, -1, 0, reg, 0); 2097 2098 /* Buffer the current row in the ephemeral table. */ 2099 if( pMWin->nBufferCol>0 ){ 2100 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg, pMWin->nBufferCol, regRecord); 2101 }else{ 2102 sqlite3VdbeAddOp2(v, OP_Blob, 0, regRecord); 2103 sqlite3VdbeAppendP4(v, (void*)"", 0); 2104 } 2105 sqlite3VdbeAddOp2(v, OP_NewRowid, pMWin->iEphCsr, regRowid); 2106 sqlite3VdbeAddOp3(v, OP_Insert, pMWin->iEphCsr, regRecord, regRowid); 2107 2108 /* End the database scan loop. */ 2109 sqlite3WhereEnd(pWInfo); 2110 2111 windowAggFinal(pParse, pMWin, 1); 2112 sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr,sqlite3VdbeCurrentAddr(v)+3); 2113 VdbeCoverage(v); 2114 sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub); 2115 sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)-1); 2116 VdbeCoverage(v); 2117 } 2118 2119 /* 2120 ** Allocate and return a duplicate of the Window object indicated by the 2121 ** third argument. Set the Window.pOwner field of the new object to 2122 ** pOwner. 2123 */ 2124 Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){ 2125 Window *pNew = 0; 2126 if( p ){ 2127 pNew = sqlite3DbMallocZero(db, sizeof(Window)); 2128 if( pNew ){ 2129 pNew->zName = sqlite3DbStrDup(db, p->zName); 2130 pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0); 2131 pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0); 2132 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0); 2133 pNew->eType = p->eType; 2134 pNew->eEnd = p->eEnd; 2135 pNew->eStart = p->eStart; 2136 pNew->pStart = sqlite3ExprDup(db, p->pStart, 0); 2137 pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0); 2138 pNew->pOwner = pOwner; 2139 } 2140 } 2141 return pNew; 2142 } 2143 2144 /* 2145 ** Return a copy of the linked list of Window objects passed as the 2146 ** second argument. 2147 */ 2148 Window *sqlite3WindowListDup(sqlite3 *db, Window *p){ 2149 Window *pWin; 2150 Window *pRet = 0; 2151 Window **pp = &pRet; 2152 2153 for(pWin=p; pWin; pWin=pWin->pNextWin){ 2154 *pp = sqlite3WindowDup(db, 0, pWin); 2155 if( *pp==0 ) break; 2156 pp = &((*pp)->pNextWin); 2157 } 2158 2159 return pRet; 2160 } 2161 2162 /* 2163 ** sqlite3WhereBegin() has already been called for the SELECT statement 2164 ** passed as the second argument when this function is invoked. It generates 2165 ** code to populate the Window.regResult register for each window function and 2166 ** invoke the sub-routine at instruction addrGosub once for each row. 2167 ** This function calls sqlite3WhereEnd() before returning. 2168 */ 2169 void sqlite3WindowCodeStep( 2170 Parse *pParse, /* Parse context */ 2171 Select *p, /* Rewritten SELECT statement */ 2172 WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */ 2173 int regGosub, /* Register for OP_Gosub */ 2174 int addrGosub /* OP_Gosub here to return each row */ 2175 ){ 2176 Window *pMWin = p->pWin; 2177 2178 /* There are three different functions that may be used to do the work 2179 ** of this one, depending on the window frame and the specific built-in 2180 ** window functions used (if any). 2181 ** 2182 ** windowCodeRowExprStep() handles all "ROWS" window frames, except for: 2183 ** 2184 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 2185 ** 2186 ** The exception is because windowCodeRowExprStep() implements all window 2187 ** frame types by caching the entire partition in a temp table, and 2188 ** "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW" is easy enough to 2189 ** implement without such a cache. 2190 ** 2191 ** windowCodeCacheStep() is used for: 2192 ** 2193 ** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING 2194 ** 2195 ** It is also used for anything not handled by windowCodeRowExprStep() 2196 ** that invokes a built-in window function that requires the entire 2197 ** partition to be cached in a temp table before any rows are returned 2198 ** (e.g. nth_value() or percent_rank()). 2199 ** 2200 ** Finally, assuming there is no built-in window function that requires 2201 ** the partition to be cached, windowCodeDefaultStep() is used for: 2202 ** 2203 ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 2204 ** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING 2205 ** RANGE BETWEEN CURRENT ROW AND CURRENT ROW 2206 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 2207 ** 2208 ** windowCodeDefaultStep() is the only one of the three functions that 2209 ** does not cache each partition in a temp table before beginning to 2210 ** return rows. 2211 */ 2212 if( pMWin->eType==TK_ROWS 2213 && (pMWin->eStart!=TK_UNBOUNDED||pMWin->eEnd!=TK_CURRENT||!pMWin->pOrderBy) 2214 ){ 2215 VdbeModuleComment((pParse->pVdbe, "Begin RowExprStep()")); 2216 windowCodeRowExprStep(pParse, p, pWInfo, regGosub, addrGosub); 2217 }else{ 2218 Window *pWin; 2219 int bCache = 0; /* True to use CacheStep() */ 2220 2221 if( pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED ){ 2222 bCache = 1; 2223 }else{ 2224 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 2225 FuncDef *pFunc = pWin->pFunc; 2226 if( (pFunc->funcFlags & SQLITE_FUNC_WINDOW_SIZE) 2227 || (pFunc->zName==nth_valueName) 2228 || (pFunc->zName==first_valueName) 2229 || (pFunc->zName==leadName) 2230 || (pFunc->zName==lagName) 2231 ){ 2232 bCache = 1; 2233 break; 2234 } 2235 } 2236 } 2237 2238 /* Otherwise, call windowCodeDefaultStep(). */ 2239 if( bCache ){ 2240 VdbeModuleComment((pParse->pVdbe, "Begin CacheStep()")); 2241 windowCodeCacheStep(pParse, p, pWInfo, regGosub, addrGosub); 2242 }else{ 2243 VdbeModuleComment((pParse->pVdbe, "Begin DefaultStep()")); 2244 windowCodeDefaultStep(pParse, p, pWInfo, regGosub, addrGosub); 2245 } 2246 } 2247 } 2248 2249 #endif /* SQLITE_OMIT_WINDOWFUNC */ 2250