1 /* 2 ** 2018 May 08 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ************************************************************************* 12 */ 13 #include "sqliteInt.h" 14 15 #ifndef SQLITE_OMIT_WINDOWFUNC 16 17 /* 18 ** SELECT REWRITING 19 ** 20 ** Any SELECT statement that contains one or more window functions in 21 ** either the select list or ORDER BY clause (the only two places window 22 ** functions may be used) is transformed by function sqlite3WindowRewrite() 23 ** in order to support window function processing. For example, with the 24 ** schema: 25 ** 26 ** CREATE TABLE t1(a, b, c, d, e, f, g); 27 ** 28 ** the statement: 29 ** 30 ** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e; 31 ** 32 ** is transformed to: 33 ** 34 ** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM ( 35 ** SELECT a, e, c, d, b FROM t1 ORDER BY c, d 36 ** ) ORDER BY e; 37 ** 38 ** The flattening optimization is disabled when processing this transformed 39 ** SELECT statement. This allows the implementation of the window function 40 ** (in this case max()) to process rows sorted in order of (c, d), which 41 ** makes things easier for obvious reasons. More generally: 42 ** 43 ** * FROM, WHERE, GROUP BY and HAVING clauses are all moved to 44 ** the sub-query. 45 ** 46 ** * ORDER BY, LIMIT and OFFSET remain part of the parent query. 47 ** 48 ** * Terminals from each of the expression trees that make up the 49 ** select-list and ORDER BY expressions in the parent query are 50 ** selected by the sub-query. For the purposes of the transformation, 51 ** terminals are column references and aggregate functions. 52 ** 53 ** If there is more than one window function in the SELECT that uses 54 ** the same window declaration (the OVER bit), then a single scan may 55 ** be used to process more than one window function. For example: 56 ** 57 ** SELECT max(b) OVER (PARTITION BY c ORDER BY d), 58 ** min(e) OVER (PARTITION BY c ORDER BY d) 59 ** FROM t1; 60 ** 61 ** is transformed in the same way as the example above. However: 62 ** 63 ** SELECT max(b) OVER (PARTITION BY c ORDER BY d), 64 ** min(e) OVER (PARTITION BY a ORDER BY b) 65 ** FROM t1; 66 ** 67 ** Must be transformed to: 68 ** 69 ** SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM ( 70 ** SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM 71 ** SELECT a, e, c, d, b FROM t1 ORDER BY a, b 72 ** ) ORDER BY c, d 73 ** ) ORDER BY e; 74 ** 75 ** so that both min() and max() may process rows in the order defined by 76 ** their respective window declarations. 77 ** 78 ** INTERFACE WITH SELECT.C 79 ** 80 ** When processing the rewritten SELECT statement, code in select.c calls 81 ** sqlite3WhereBegin() to begin iterating through the results of the 82 ** sub-query, which is always implemented as a co-routine. It then calls 83 ** sqlite3WindowCodeStep() to process rows and finish the scan by calling 84 ** sqlite3WhereEnd(). 85 ** 86 ** sqlite3WindowCodeStep() generates VM code so that, for each row returned 87 ** by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked. 88 ** When the sub-routine is invoked: 89 ** 90 ** * The results of all window-functions for the row are stored 91 ** in the associated Window.regResult registers. 92 ** 93 ** * The required terminal values are stored in the current row of 94 ** temp table Window.iEphCsr. 95 ** 96 ** In some cases, depending on the window frame and the specific window 97 ** functions invoked, sqlite3WindowCodeStep() caches each entire partition 98 ** in a temp table before returning any rows. In other cases it does not. 99 ** This detail is encapsulated within this file, the code generated by 100 ** select.c is the same in either case. 101 ** 102 ** BUILT-IN WINDOW FUNCTIONS 103 ** 104 ** This implementation features the following built-in window functions: 105 ** 106 ** row_number() 107 ** rank() 108 ** dense_rank() 109 ** percent_rank() 110 ** cume_dist() 111 ** ntile(N) 112 ** lead(expr [, offset [, default]]) 113 ** lag(expr [, offset [, default]]) 114 ** first_value(expr) 115 ** last_value(expr) 116 ** nth_value(expr, N) 117 ** 118 ** These are the same built-in window functions supported by Postgres. 119 ** Although the behaviour of aggregate window functions (functions that 120 ** can be used as either aggregates or window funtions) allows them to 121 ** be implemented using an API, built-in window functions are much more 122 ** esoteric. Additionally, some window functions (e.g. nth_value()) 123 ** may only be implemented by caching the entire partition in memory. 124 ** As such, some built-in window functions use the same API as aggregate 125 ** window functions and some are implemented directly using VDBE 126 ** instructions. Additionally, for those functions that use the API, the 127 ** window frame is sometimes modified before the SELECT statement is 128 ** rewritten. For example, regardless of the specified window frame, the 129 ** row_number() function always uses: 130 ** 131 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 132 ** 133 ** See sqlite3WindowUpdate() for details. 134 ** 135 ** As well as some of the built-in window functions, aggregate window 136 ** functions min() and max() are implemented using VDBE instructions if 137 ** the start of the window frame is declared as anything other than 138 ** UNBOUNDED PRECEDING. 139 */ 140 141 /* 142 ** Implementation of built-in window function row_number(). Assumes that the 143 ** window frame has been coerced to: 144 ** 145 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 146 */ 147 static void row_numberStepFunc( 148 sqlite3_context *pCtx, 149 int nArg, 150 sqlite3_value **apArg 151 ){ 152 i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 153 if( p ) (*p)++; 154 UNUSED_PARAMETER(nArg); 155 UNUSED_PARAMETER(apArg); 156 } 157 static void row_numberValueFunc(sqlite3_context *pCtx){ 158 i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 159 sqlite3_result_int64(pCtx, (p ? *p : 0)); 160 } 161 162 /* 163 ** Context object type used by rank(), dense_rank(), percent_rank() and 164 ** cume_dist(). 165 */ 166 struct CallCount { 167 i64 nValue; 168 i64 nStep; 169 i64 nTotal; 170 }; 171 172 /* 173 ** Implementation of built-in window function dense_rank(). Assumes that 174 ** the window frame has been set to: 175 ** 176 ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 177 */ 178 static void dense_rankStepFunc( 179 sqlite3_context *pCtx, 180 int nArg, 181 sqlite3_value **apArg 182 ){ 183 struct CallCount *p; 184 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 185 if( p ) p->nStep = 1; 186 UNUSED_PARAMETER(nArg); 187 UNUSED_PARAMETER(apArg); 188 } 189 static void dense_rankValueFunc(sqlite3_context *pCtx){ 190 struct CallCount *p; 191 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 192 if( p ){ 193 if( p->nStep ){ 194 p->nValue++; 195 p->nStep = 0; 196 } 197 sqlite3_result_int64(pCtx, p->nValue); 198 } 199 } 200 201 /* 202 ** Implementation of built-in window function nth_value(). This 203 ** implementation is used in "slow mode" only - when the EXCLUDE clause 204 ** is not set to the default value "NO OTHERS". 205 */ 206 struct NthValueCtx { 207 i64 nStep; 208 sqlite3_value *pValue; 209 }; 210 static void nth_valueStepFunc( 211 sqlite3_context *pCtx, 212 int nArg, 213 sqlite3_value **apArg 214 ){ 215 struct NthValueCtx *p; 216 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 217 if( p ){ 218 i64 iVal; 219 switch( sqlite3_value_numeric_type(apArg[1]) ){ 220 case SQLITE_INTEGER: 221 iVal = sqlite3_value_int64(apArg[1]); 222 break; 223 case SQLITE_FLOAT: { 224 double fVal = sqlite3_value_double(apArg[1]); 225 if( ((i64)fVal)!=fVal ) goto error_out; 226 iVal = (i64)fVal; 227 break; 228 } 229 default: 230 goto error_out; 231 } 232 if( iVal<=0 ) goto error_out; 233 234 p->nStep++; 235 if( iVal==p->nStep ){ 236 p->pValue = sqlite3_value_dup(apArg[0]); 237 if( !p->pValue ){ 238 sqlite3_result_error_nomem(pCtx); 239 } 240 } 241 } 242 UNUSED_PARAMETER(nArg); 243 UNUSED_PARAMETER(apArg); 244 return; 245 246 error_out: 247 sqlite3_result_error( 248 pCtx, "second argument to nth_value must be a positive integer", -1 249 ); 250 } 251 static void nth_valueFinalizeFunc(sqlite3_context *pCtx){ 252 struct NthValueCtx *p; 253 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, 0); 254 if( p && p->pValue ){ 255 sqlite3_result_value(pCtx, p->pValue); 256 sqlite3_value_free(p->pValue); 257 p->pValue = 0; 258 } 259 } 260 #define nth_valueInvFunc noopStepFunc 261 #define nth_valueValueFunc noopValueFunc 262 263 static void first_valueStepFunc( 264 sqlite3_context *pCtx, 265 int nArg, 266 sqlite3_value **apArg 267 ){ 268 struct NthValueCtx *p; 269 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 270 if( p && p->pValue==0 ){ 271 p->pValue = sqlite3_value_dup(apArg[0]); 272 if( !p->pValue ){ 273 sqlite3_result_error_nomem(pCtx); 274 } 275 } 276 UNUSED_PARAMETER(nArg); 277 UNUSED_PARAMETER(apArg); 278 } 279 static void first_valueFinalizeFunc(sqlite3_context *pCtx){ 280 struct NthValueCtx *p; 281 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 282 if( p && p->pValue ){ 283 sqlite3_result_value(pCtx, p->pValue); 284 sqlite3_value_free(p->pValue); 285 p->pValue = 0; 286 } 287 } 288 #define first_valueInvFunc noopStepFunc 289 #define first_valueValueFunc noopValueFunc 290 291 /* 292 ** Implementation of built-in window function rank(). Assumes that 293 ** the window frame has been set to: 294 ** 295 ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 296 */ 297 static void rankStepFunc( 298 sqlite3_context *pCtx, 299 int nArg, 300 sqlite3_value **apArg 301 ){ 302 struct CallCount *p; 303 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 304 if( p ){ 305 p->nStep++; 306 if( p->nValue==0 ){ 307 p->nValue = p->nStep; 308 } 309 } 310 UNUSED_PARAMETER(nArg); 311 UNUSED_PARAMETER(apArg); 312 } 313 static void rankValueFunc(sqlite3_context *pCtx){ 314 struct CallCount *p; 315 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 316 if( p ){ 317 sqlite3_result_int64(pCtx, p->nValue); 318 p->nValue = 0; 319 } 320 } 321 322 /* 323 ** Implementation of built-in window function percent_rank(). Assumes that 324 ** the window frame has been set to: 325 ** 326 ** GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING 327 */ 328 static void percent_rankStepFunc( 329 sqlite3_context *pCtx, 330 int nArg, 331 sqlite3_value **apArg 332 ){ 333 struct CallCount *p; 334 UNUSED_PARAMETER(nArg); assert( nArg==0 ); 335 UNUSED_PARAMETER(apArg); 336 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 337 if( p ){ 338 p->nTotal++; 339 } 340 } 341 static void percent_rankInvFunc( 342 sqlite3_context *pCtx, 343 int nArg, 344 sqlite3_value **apArg 345 ){ 346 struct CallCount *p; 347 UNUSED_PARAMETER(nArg); assert( nArg==0 ); 348 UNUSED_PARAMETER(apArg); 349 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 350 p->nStep++; 351 } 352 static void percent_rankValueFunc(sqlite3_context *pCtx){ 353 struct CallCount *p; 354 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 355 if( p ){ 356 p->nValue = p->nStep; 357 if( p->nTotal>1 ){ 358 double r = (double)p->nValue / (double)(p->nTotal-1); 359 sqlite3_result_double(pCtx, r); 360 }else{ 361 sqlite3_result_double(pCtx, 0.0); 362 } 363 } 364 } 365 #define percent_rankFinalizeFunc percent_rankValueFunc 366 367 /* 368 ** Implementation of built-in window function cume_dist(). Assumes that 369 ** the window frame has been set to: 370 ** 371 ** GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING 372 */ 373 static void cume_distStepFunc( 374 sqlite3_context *pCtx, 375 int nArg, 376 sqlite3_value **apArg 377 ){ 378 struct CallCount *p; 379 UNUSED_PARAMETER(nArg); assert( nArg==0 ); 380 UNUSED_PARAMETER(apArg); 381 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 382 if( p ){ 383 p->nTotal++; 384 } 385 } 386 static void cume_distInvFunc( 387 sqlite3_context *pCtx, 388 int nArg, 389 sqlite3_value **apArg 390 ){ 391 struct CallCount *p; 392 UNUSED_PARAMETER(nArg); assert( nArg==0 ); 393 UNUSED_PARAMETER(apArg); 394 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 395 p->nStep++; 396 } 397 static void cume_distValueFunc(sqlite3_context *pCtx){ 398 struct CallCount *p; 399 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, 0); 400 if( p ){ 401 double r = (double)(p->nStep) / (double)(p->nTotal); 402 sqlite3_result_double(pCtx, r); 403 } 404 } 405 #define cume_distFinalizeFunc cume_distValueFunc 406 407 /* 408 ** Context object for ntile() window function. 409 */ 410 struct NtileCtx { 411 i64 nTotal; /* Total rows in partition */ 412 i64 nParam; /* Parameter passed to ntile(N) */ 413 i64 iRow; /* Current row */ 414 }; 415 416 /* 417 ** Implementation of ntile(). This assumes that the window frame has 418 ** been coerced to: 419 ** 420 ** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING 421 */ 422 static void ntileStepFunc( 423 sqlite3_context *pCtx, 424 int nArg, 425 sqlite3_value **apArg 426 ){ 427 struct NtileCtx *p; 428 assert( nArg==1 ); UNUSED_PARAMETER(nArg); 429 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 430 if( p ){ 431 if( p->nTotal==0 ){ 432 p->nParam = sqlite3_value_int64(apArg[0]); 433 if( p->nParam<=0 ){ 434 sqlite3_result_error( 435 pCtx, "argument of ntile must be a positive integer", -1 436 ); 437 } 438 } 439 p->nTotal++; 440 } 441 } 442 static void ntileInvFunc( 443 sqlite3_context *pCtx, 444 int nArg, 445 sqlite3_value **apArg 446 ){ 447 struct NtileCtx *p; 448 assert( nArg==1 ); UNUSED_PARAMETER(nArg); 449 UNUSED_PARAMETER(apArg); 450 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 451 p->iRow++; 452 } 453 static void ntileValueFunc(sqlite3_context *pCtx){ 454 struct NtileCtx *p; 455 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 456 if( p && p->nParam>0 ){ 457 int nSize = (p->nTotal / p->nParam); 458 if( nSize==0 ){ 459 sqlite3_result_int64(pCtx, p->iRow+1); 460 }else{ 461 i64 nLarge = p->nTotal - p->nParam*nSize; 462 i64 iSmall = nLarge*(nSize+1); 463 i64 iRow = p->iRow; 464 465 assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal ); 466 467 if( iRow<iSmall ){ 468 sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1)); 469 }else{ 470 sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize); 471 } 472 } 473 } 474 } 475 #define ntileFinalizeFunc ntileValueFunc 476 477 /* 478 ** Context object for last_value() window function. 479 */ 480 struct LastValueCtx { 481 sqlite3_value *pVal; 482 int nVal; 483 }; 484 485 /* 486 ** Implementation of last_value(). 487 */ 488 static void last_valueStepFunc( 489 sqlite3_context *pCtx, 490 int nArg, 491 sqlite3_value **apArg 492 ){ 493 struct LastValueCtx *p; 494 UNUSED_PARAMETER(nArg); 495 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 496 if( p ){ 497 sqlite3_value_free(p->pVal); 498 p->pVal = sqlite3_value_dup(apArg[0]); 499 if( p->pVal==0 ){ 500 sqlite3_result_error_nomem(pCtx); 501 }else{ 502 p->nVal++; 503 } 504 } 505 } 506 static void last_valueInvFunc( 507 sqlite3_context *pCtx, 508 int nArg, 509 sqlite3_value **apArg 510 ){ 511 struct LastValueCtx *p; 512 UNUSED_PARAMETER(nArg); 513 UNUSED_PARAMETER(apArg); 514 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 515 if( ALWAYS(p) ){ 516 p->nVal--; 517 if( p->nVal==0 ){ 518 sqlite3_value_free(p->pVal); 519 p->pVal = 0; 520 } 521 } 522 } 523 static void last_valueValueFunc(sqlite3_context *pCtx){ 524 struct LastValueCtx *p; 525 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, 0); 526 if( p && p->pVal ){ 527 sqlite3_result_value(pCtx, p->pVal); 528 } 529 } 530 static void last_valueFinalizeFunc(sqlite3_context *pCtx){ 531 struct LastValueCtx *p; 532 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 533 if( p && p->pVal ){ 534 sqlite3_result_value(pCtx, p->pVal); 535 sqlite3_value_free(p->pVal); 536 p->pVal = 0; 537 } 538 } 539 540 /* 541 ** Static names for the built-in window function names. These static 542 ** names are used, rather than string literals, so that FuncDef objects 543 ** can be associated with a particular window function by direct 544 ** comparison of the zName pointer. Example: 545 ** 546 ** if( pFuncDef->zName==row_valueName ){ ... } 547 */ 548 static const char row_numberName[] = "row_number"; 549 static const char dense_rankName[] = "dense_rank"; 550 static const char rankName[] = "rank"; 551 static const char percent_rankName[] = "percent_rank"; 552 static const char cume_distName[] = "cume_dist"; 553 static const char ntileName[] = "ntile"; 554 static const char last_valueName[] = "last_value"; 555 static const char nth_valueName[] = "nth_value"; 556 static const char first_valueName[] = "first_value"; 557 static const char leadName[] = "lead"; 558 static const char lagName[] = "lag"; 559 560 /* 561 ** No-op implementations of xStep() and xFinalize(). Used as place-holders 562 ** for built-in window functions that never call those interfaces. 563 ** 564 ** The noopValueFunc() is called but is expected to do nothing. The 565 ** noopStepFunc() is never called, and so it is marked with NO_TEST to 566 ** let the test coverage routine know not to expect this function to be 567 ** invoked. 568 */ 569 static void noopStepFunc( /*NO_TEST*/ 570 sqlite3_context *p, /*NO_TEST*/ 571 int n, /*NO_TEST*/ 572 sqlite3_value **a /*NO_TEST*/ 573 ){ /*NO_TEST*/ 574 UNUSED_PARAMETER(p); /*NO_TEST*/ 575 UNUSED_PARAMETER(n); /*NO_TEST*/ 576 UNUSED_PARAMETER(a); /*NO_TEST*/ 577 assert(0); /*NO_TEST*/ 578 } /*NO_TEST*/ 579 static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ } 580 581 /* Window functions that use all window interfaces: xStep, xFinal, 582 ** xValue, and xInverse */ 583 #define WINDOWFUNCALL(name,nArg,extra) { \ 584 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \ 585 name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \ 586 name ## InvFunc, name ## Name, {0} \ 587 } 588 589 /* Window functions that are implemented using bytecode and thus have 590 ** no-op routines for their methods */ 591 #define WINDOWFUNCNOOP(name,nArg,extra) { \ 592 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \ 593 noopStepFunc, noopValueFunc, noopValueFunc, \ 594 noopStepFunc, name ## Name, {0} \ 595 } 596 597 /* Window functions that use all window interfaces: xStep, the 598 ** same routine for xFinalize and xValue and which never call 599 ** xInverse. */ 600 #define WINDOWFUNCX(name,nArg,extra) { \ 601 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \ 602 name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \ 603 noopStepFunc, name ## Name, {0} \ 604 } 605 606 607 /* 608 ** Register those built-in window functions that are not also aggregates. 609 */ 610 void sqlite3WindowFunctions(void){ 611 static FuncDef aWindowFuncs[] = { 612 WINDOWFUNCX(row_number, 0, 0), 613 WINDOWFUNCX(dense_rank, 0, 0), 614 WINDOWFUNCX(rank, 0, 0), 615 WINDOWFUNCALL(percent_rank, 0, 0), 616 WINDOWFUNCALL(cume_dist, 0, 0), 617 WINDOWFUNCALL(ntile, 1, 0), 618 WINDOWFUNCALL(last_value, 1, 0), 619 WINDOWFUNCALL(nth_value, 2, 0), 620 WINDOWFUNCALL(first_value, 1, 0), 621 WINDOWFUNCNOOP(lead, 1, 0), 622 WINDOWFUNCNOOP(lead, 2, 0), 623 WINDOWFUNCNOOP(lead, 3, 0), 624 WINDOWFUNCNOOP(lag, 1, 0), 625 WINDOWFUNCNOOP(lag, 2, 0), 626 WINDOWFUNCNOOP(lag, 3, 0), 627 }; 628 sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs)); 629 } 630 631 static Window *windowFind(Parse *pParse, Window *pList, const char *zName){ 632 Window *p; 633 for(p=pList; p; p=p->pNextWin){ 634 if( sqlite3StrICmp(p->zName, zName)==0 ) break; 635 } 636 if( p==0 ){ 637 sqlite3ErrorMsg(pParse, "no such window: %s", zName); 638 } 639 return p; 640 } 641 642 /* 643 ** This function is called immediately after resolving the function name 644 ** for a window function within a SELECT statement. Argument pList is a 645 ** linked list of WINDOW definitions for the current SELECT statement. 646 ** Argument pFunc is the function definition just resolved and pWin 647 ** is the Window object representing the associated OVER clause. This 648 ** function updates the contents of pWin as follows: 649 ** 650 ** * If the OVER clause refered to a named window (as in "max(x) OVER win"), 651 ** search list pList for a matching WINDOW definition, and update pWin 652 ** accordingly. If no such WINDOW clause can be found, leave an error 653 ** in pParse. 654 ** 655 ** * If the function is a built-in window function that requires the 656 ** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top 657 ** of this file), pWin is updated here. 658 */ 659 void sqlite3WindowUpdate( 660 Parse *pParse, 661 Window *pList, /* List of named windows for this SELECT */ 662 Window *pWin, /* Window frame to update */ 663 FuncDef *pFunc /* Window function definition */ 664 ){ 665 if( pWin->zName && pWin->eFrmType==0 ){ 666 Window *p = windowFind(pParse, pList, pWin->zName); 667 if( p==0 ) return; 668 pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0); 669 pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0); 670 pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0); 671 pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0); 672 pWin->eStart = p->eStart; 673 pWin->eEnd = p->eEnd; 674 pWin->eFrmType = p->eFrmType; 675 pWin->eExclude = p->eExclude; 676 }else{ 677 sqlite3WindowChain(pParse, pWin, pList); 678 } 679 if( (pWin->eFrmType==TK_RANGE) 680 && (pWin->pStart || pWin->pEnd) 681 && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1) 682 ){ 683 sqlite3ErrorMsg(pParse, 684 "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression" 685 ); 686 }else 687 if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){ 688 sqlite3 *db = pParse->db; 689 if( pWin->pFilter ){ 690 sqlite3ErrorMsg(pParse, 691 "FILTER clause may only be used with aggregate window functions" 692 ); 693 }else{ 694 struct WindowUpdate { 695 const char *zFunc; 696 int eFrmType; 697 int eStart; 698 int eEnd; 699 } aUp[] = { 700 { row_numberName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT }, 701 { dense_rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT }, 702 { rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT }, 703 { percent_rankName, TK_GROUPS, TK_CURRENT, TK_UNBOUNDED }, 704 { cume_distName, TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED }, 705 { ntileName, TK_ROWS, TK_CURRENT, TK_UNBOUNDED }, 706 { leadName, TK_ROWS, TK_UNBOUNDED, TK_UNBOUNDED }, 707 { lagName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT }, 708 }; 709 int i; 710 for(i=0; i<ArraySize(aUp); i++){ 711 if( pFunc->zName==aUp[i].zFunc ){ 712 sqlite3ExprDelete(db, pWin->pStart); 713 sqlite3ExprDelete(db, pWin->pEnd); 714 pWin->pEnd = pWin->pStart = 0; 715 pWin->eFrmType = aUp[i].eFrmType; 716 pWin->eStart = aUp[i].eStart; 717 pWin->eEnd = aUp[i].eEnd; 718 pWin->eExclude = 0; 719 if( pWin->eStart==TK_FOLLOWING ){ 720 pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1"); 721 } 722 break; 723 } 724 } 725 } 726 } 727 pWin->pFunc = pFunc; 728 } 729 730 /* 731 ** Context object passed through sqlite3WalkExprList() to 732 ** selectWindowRewriteExprCb() by selectWindowRewriteEList(). 733 */ 734 typedef struct WindowRewrite WindowRewrite; 735 struct WindowRewrite { 736 Window *pWin; 737 SrcList *pSrc; 738 ExprList *pSub; 739 Table *pTab; 740 Select *pSubSelect; /* Current sub-select, if any */ 741 }; 742 743 /* 744 ** Callback function used by selectWindowRewriteEList(). If necessary, 745 ** this function appends to the output expression-list and updates 746 ** expression (*ppExpr) in place. 747 */ 748 static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){ 749 struct WindowRewrite *p = pWalker->u.pRewrite; 750 Parse *pParse = pWalker->pParse; 751 assert( p!=0 ); 752 assert( p->pWin!=0 ); 753 754 /* If this function is being called from within a scalar sub-select 755 ** that used by the SELECT statement being processed, only process 756 ** TK_COLUMN expressions that refer to it (the outer SELECT). Do 757 ** not process aggregates or window functions at all, as they belong 758 ** to the scalar sub-select. */ 759 if( p->pSubSelect ){ 760 if( pExpr->op!=TK_COLUMN ){ 761 return WRC_Continue; 762 }else{ 763 int nSrc = p->pSrc->nSrc; 764 int i; 765 for(i=0; i<nSrc; i++){ 766 if( pExpr->iTable==p->pSrc->a[i].iCursor ) break; 767 } 768 if( i==nSrc ) return WRC_Continue; 769 } 770 } 771 772 switch( pExpr->op ){ 773 774 case TK_FUNCTION: 775 if( !ExprHasProperty(pExpr, EP_WinFunc) ){ 776 break; 777 }else{ 778 Window *pWin; 779 for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){ 780 if( pExpr->y.pWin==pWin ){ 781 assert( pWin->pOwner==pExpr ); 782 return WRC_Prune; 783 } 784 } 785 } 786 /* Fall through. */ 787 788 case TK_AGG_FUNCTION: 789 case TK_COLUMN: { 790 Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0); 791 p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup); 792 if( p->pSub ){ 793 assert( ExprHasProperty(pExpr, EP_Static)==0 ); 794 ExprSetProperty(pExpr, EP_Static); 795 sqlite3ExprDelete(pParse->db, pExpr); 796 ExprClearProperty(pExpr, EP_Static); 797 memset(pExpr, 0, sizeof(Expr)); 798 799 pExpr->op = TK_COLUMN; 800 pExpr->iColumn = p->pSub->nExpr-1; 801 pExpr->iTable = p->pWin->iEphCsr; 802 pExpr->y.pTab = p->pTab; 803 } 804 805 break; 806 } 807 808 default: /* no-op */ 809 break; 810 } 811 812 return WRC_Continue; 813 } 814 static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){ 815 struct WindowRewrite *p = pWalker->u.pRewrite; 816 Select *pSave = p->pSubSelect; 817 if( pSave==pSelect ){ 818 return WRC_Continue; 819 }else{ 820 p->pSubSelect = pSelect; 821 sqlite3WalkSelect(pWalker, pSelect); 822 p->pSubSelect = pSave; 823 } 824 return WRC_Prune; 825 } 826 827 828 /* 829 ** Iterate through each expression in expression-list pEList. For each: 830 ** 831 ** * TK_COLUMN, 832 ** * aggregate function, or 833 ** * window function with a Window object that is not a member of the 834 ** Window list passed as the second argument (pWin). 835 ** 836 ** Append the node to output expression-list (*ppSub). And replace it 837 ** with a TK_COLUMN that reads the (N-1)th element of table 838 ** pWin->iEphCsr, where N is the number of elements in (*ppSub) after 839 ** appending the new one. 840 */ 841 static void selectWindowRewriteEList( 842 Parse *pParse, 843 Window *pWin, 844 SrcList *pSrc, 845 ExprList *pEList, /* Rewrite expressions in this list */ 846 Table *pTab, 847 ExprList **ppSub /* IN/OUT: Sub-select expression-list */ 848 ){ 849 Walker sWalker; 850 WindowRewrite sRewrite; 851 852 assert( pWin!=0 ); 853 memset(&sWalker, 0, sizeof(Walker)); 854 memset(&sRewrite, 0, sizeof(WindowRewrite)); 855 856 sRewrite.pSub = *ppSub; 857 sRewrite.pWin = pWin; 858 sRewrite.pSrc = pSrc; 859 sRewrite.pTab = pTab; 860 861 sWalker.pParse = pParse; 862 sWalker.xExprCallback = selectWindowRewriteExprCb; 863 sWalker.xSelectCallback = selectWindowRewriteSelectCb; 864 sWalker.u.pRewrite = &sRewrite; 865 866 (void)sqlite3WalkExprList(&sWalker, pEList); 867 868 *ppSub = sRewrite.pSub; 869 } 870 871 /* 872 ** Append a copy of each expression in expression-list pAppend to 873 ** expression list pList. Return a pointer to the result list. 874 */ 875 static ExprList *exprListAppendList( 876 Parse *pParse, /* Parsing context */ 877 ExprList *pList, /* List to which to append. Might be NULL */ 878 ExprList *pAppend, /* List of values to append. Might be NULL */ 879 int bIntToNull 880 ){ 881 if( pAppend ){ 882 int i; 883 int nInit = pList ? pList->nExpr : 0; 884 for(i=0; i<pAppend->nExpr; i++){ 885 Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0); 886 if( bIntToNull && pDup && pDup->op==TK_INTEGER ){ 887 pDup->op = TK_NULL; 888 pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse); 889 } 890 pList = sqlite3ExprListAppend(pParse, pList, pDup); 891 if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags; 892 } 893 } 894 return pList; 895 } 896 897 /* 898 ** If the SELECT statement passed as the second argument does not invoke 899 ** any SQL window functions, this function is a no-op. Otherwise, it 900 ** rewrites the SELECT statement so that window function xStep functions 901 ** are invoked in the correct order as described under "SELECT REWRITING" 902 ** at the top of this file. 903 */ 904 int sqlite3WindowRewrite(Parse *pParse, Select *p){ 905 int rc = SQLITE_OK; 906 if( p->pWin && p->pPrior==0 ){ 907 Vdbe *v = sqlite3GetVdbe(pParse); 908 sqlite3 *db = pParse->db; 909 Select *pSub = 0; /* The subquery */ 910 SrcList *pSrc = p->pSrc; 911 Expr *pWhere = p->pWhere; 912 ExprList *pGroupBy = p->pGroupBy; 913 Expr *pHaving = p->pHaving; 914 ExprList *pSort = 0; 915 916 ExprList *pSublist = 0; /* Expression list for sub-query */ 917 Window *pMWin = p->pWin; /* Master window object */ 918 Window *pWin; /* Window object iterator */ 919 Table *pTab; 920 921 pTab = sqlite3DbMallocZero(db, sizeof(Table)); 922 if( pTab==0 ){ 923 return SQLITE_NOMEM; 924 } 925 926 p->pSrc = 0; 927 p->pWhere = 0; 928 p->pGroupBy = 0; 929 p->pHaving = 0; 930 p->selFlags &= ~SF_Aggregate; 931 932 /* Create the ORDER BY clause for the sub-select. This is the concatenation 933 ** of the window PARTITION and ORDER BY clauses. Then, if this makes it 934 ** redundant, remove the ORDER BY from the parent SELECT. */ 935 pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0); 936 pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1); 937 if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){ 938 int nSave = pSort->nExpr; 939 pSort->nExpr = p->pOrderBy->nExpr; 940 if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){ 941 sqlite3ExprListDelete(db, p->pOrderBy); 942 p->pOrderBy = 0; 943 } 944 pSort->nExpr = nSave; 945 } 946 947 /* Assign a cursor number for the ephemeral table used to buffer rows. 948 ** The OpenEphemeral instruction is coded later, after it is known how 949 ** many columns the table will have. */ 950 pMWin->iEphCsr = pParse->nTab++; 951 pParse->nTab += 3; 952 953 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist); 954 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist); 955 pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0); 956 957 /* Append the PARTITION BY and ORDER BY expressions to the to the 958 ** sub-select expression list. They are required to figure out where 959 ** boundaries for partitions and sets of peer rows lie. */ 960 pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0); 961 pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0); 962 963 /* Append the arguments passed to each window function to the 964 ** sub-select expression list. Also allocate two registers for each 965 ** window function - one for the accumulator, another for interim 966 ** results. */ 967 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 968 ExprList *pArgs = pWin->pOwner->x.pList; 969 if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){ 970 selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist); 971 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0); 972 pWin->bExprArgs = 1; 973 }else{ 974 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0); 975 pSublist = exprListAppendList(pParse, pSublist, pArgs, 0); 976 } 977 if( pWin->pFilter ){ 978 Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0); 979 pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter); 980 } 981 pWin->regAccum = ++pParse->nMem; 982 pWin->regResult = ++pParse->nMem; 983 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); 984 } 985 986 /* If there is no ORDER BY or PARTITION BY clause, and the window 987 ** function accepts zero arguments, and there are no other columns 988 ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible 989 ** that pSublist is still NULL here. Add a constant expression here to 990 ** keep everything legal in this case. 991 */ 992 if( pSublist==0 ){ 993 pSublist = sqlite3ExprListAppend(pParse, 0, 994 sqlite3Expr(db, TK_INTEGER, "0") 995 ); 996 } 997 998 pSub = sqlite3SelectNew( 999 pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0 1000 ); 1001 p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0); 1002 if( p->pSrc ){ 1003 Table *pTab2; 1004 p->pSrc->a[0].pSelect = pSub; 1005 sqlite3SrcListAssignCursors(pParse, p->pSrc); 1006 pSub->selFlags |= SF_Expanded; 1007 pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE); 1008 if( pTab2==0 ){ 1009 rc = SQLITE_NOMEM; 1010 }else{ 1011 memcpy(pTab, pTab2, sizeof(Table)); 1012 pTab->tabFlags |= TF_Ephemeral; 1013 p->pSrc->a[0].pTab = pTab; 1014 pTab = pTab2; 1015 } 1016 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr); 1017 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr); 1018 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr); 1019 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr); 1020 }else{ 1021 sqlite3SelectDelete(db, pSub); 1022 } 1023 if( db->mallocFailed ) rc = SQLITE_NOMEM; 1024 sqlite3DbFree(db, pTab); 1025 } 1026 1027 return rc; 1028 } 1029 1030 /* 1031 ** Unlink the Window object from the Select to which it is attached, 1032 ** if it is attached. 1033 */ 1034 void sqlite3WindowUnlinkFromSelect(Window *p){ 1035 if( p->ppThis ){ 1036 *p->ppThis = p->pNextWin; 1037 if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis; 1038 p->ppThis = 0; 1039 } 1040 } 1041 1042 /* 1043 ** Free the Window object passed as the second argument. 1044 */ 1045 void sqlite3WindowDelete(sqlite3 *db, Window *p){ 1046 if( p ){ 1047 sqlite3WindowUnlinkFromSelect(p); 1048 sqlite3ExprDelete(db, p->pFilter); 1049 sqlite3ExprListDelete(db, p->pPartition); 1050 sqlite3ExprListDelete(db, p->pOrderBy); 1051 sqlite3ExprDelete(db, p->pEnd); 1052 sqlite3ExprDelete(db, p->pStart); 1053 sqlite3DbFree(db, p->zName); 1054 sqlite3DbFree(db, p->zBase); 1055 sqlite3DbFree(db, p); 1056 } 1057 } 1058 1059 /* 1060 ** Free the linked list of Window objects starting at the second argument. 1061 */ 1062 void sqlite3WindowListDelete(sqlite3 *db, Window *p){ 1063 while( p ){ 1064 Window *pNext = p->pNextWin; 1065 sqlite3WindowDelete(db, p); 1066 p = pNext; 1067 } 1068 } 1069 1070 /* 1071 ** The argument expression is an PRECEDING or FOLLOWING offset. The 1072 ** value should be a non-negative integer. If the value is not a 1073 ** constant, change it to NULL. The fact that it is then a non-negative 1074 ** integer will be caught later. But it is important not to leave 1075 ** variable values in the expression tree. 1076 */ 1077 static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){ 1078 if( 0==sqlite3ExprIsConstant(pExpr) ){ 1079 if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr); 1080 sqlite3ExprDelete(pParse->db, pExpr); 1081 pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0); 1082 } 1083 return pExpr; 1084 } 1085 1086 /* 1087 ** Allocate and return a new Window object describing a Window Definition. 1088 */ 1089 Window *sqlite3WindowAlloc( 1090 Parse *pParse, /* Parsing context */ 1091 int eType, /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */ 1092 int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */ 1093 Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */ 1094 int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */ 1095 Expr *pEnd, /* End window size if TK_FOLLOWING or PRECEDING */ 1096 u8 eExclude /* EXCLUDE clause */ 1097 ){ 1098 Window *pWin = 0; 1099 int bImplicitFrame = 0; 1100 1101 /* Parser assures the following: */ 1102 assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS ); 1103 assert( eStart==TK_CURRENT || eStart==TK_PRECEDING 1104 || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING ); 1105 assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING 1106 || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING ); 1107 assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) ); 1108 assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) ); 1109 1110 if( eType==0 ){ 1111 bImplicitFrame = 1; 1112 eType = TK_RANGE; 1113 } 1114 1115 /* Additionally, the 1116 ** starting boundary type may not occur earlier in the following list than 1117 ** the ending boundary type: 1118 ** 1119 ** UNBOUNDED PRECEDING 1120 ** <expr> PRECEDING 1121 ** CURRENT ROW 1122 ** <expr> FOLLOWING 1123 ** UNBOUNDED FOLLOWING 1124 ** 1125 ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending 1126 ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting 1127 ** frame boundary. 1128 */ 1129 if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING) 1130 || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT)) 1131 ){ 1132 sqlite3ErrorMsg(pParse, "unsupported frame specification"); 1133 goto windowAllocErr; 1134 } 1135 1136 pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window)); 1137 if( pWin==0 ) goto windowAllocErr; 1138 pWin->eFrmType = eType; 1139 pWin->eStart = eStart; 1140 pWin->eEnd = eEnd; 1141 if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){ 1142 eExclude = TK_NO; 1143 } 1144 pWin->eExclude = eExclude; 1145 pWin->bImplicitFrame = bImplicitFrame; 1146 pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd); 1147 pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart); 1148 return pWin; 1149 1150 windowAllocErr: 1151 sqlite3ExprDelete(pParse->db, pEnd); 1152 sqlite3ExprDelete(pParse->db, pStart); 1153 return 0; 1154 } 1155 1156 /* 1157 ** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window 1158 ** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the 1159 ** equivalent nul-terminated string. 1160 */ 1161 Window *sqlite3WindowAssemble( 1162 Parse *pParse, 1163 Window *pWin, 1164 ExprList *pPartition, 1165 ExprList *pOrderBy, 1166 Token *pBase 1167 ){ 1168 if( pWin ){ 1169 pWin->pPartition = pPartition; 1170 pWin->pOrderBy = pOrderBy; 1171 if( pBase ){ 1172 pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n); 1173 } 1174 }else{ 1175 sqlite3ExprListDelete(pParse->db, pPartition); 1176 sqlite3ExprListDelete(pParse->db, pOrderBy); 1177 } 1178 return pWin; 1179 } 1180 1181 /* 1182 ** Window *pWin has just been created from a WINDOW clause. Tokne pBase 1183 ** is the base window. Earlier windows from the same WINDOW clause are 1184 ** stored in the linked list starting at pWin->pNextWin. This function 1185 ** either updates *pWin according to the base specification, or else 1186 ** leaves an error in pParse. 1187 */ 1188 void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){ 1189 if( pWin->zBase ){ 1190 sqlite3 *db = pParse->db; 1191 Window *pExist = windowFind(pParse, pList, pWin->zBase); 1192 if( pExist ){ 1193 const char *zErr = 0; 1194 /* Check for errors */ 1195 if( pWin->pPartition ){ 1196 zErr = "PARTITION clause"; 1197 }else if( pExist->pOrderBy && pWin->pOrderBy ){ 1198 zErr = "ORDER BY clause"; 1199 }else if( pExist->bImplicitFrame==0 ){ 1200 zErr = "frame specification"; 1201 } 1202 if( zErr ){ 1203 sqlite3ErrorMsg(pParse, 1204 "cannot override %s of window: %s", zErr, pWin->zBase 1205 ); 1206 }else{ 1207 pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0); 1208 if( pExist->pOrderBy ){ 1209 assert( pWin->pOrderBy==0 ); 1210 pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0); 1211 } 1212 sqlite3DbFree(db, pWin->zBase); 1213 pWin->zBase = 0; 1214 } 1215 } 1216 } 1217 } 1218 1219 /* 1220 ** Attach window object pWin to expression p. 1221 */ 1222 void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){ 1223 if( p ){ 1224 assert( p->op==TK_FUNCTION ); 1225 assert( pWin ); 1226 p->y.pWin = pWin; 1227 ExprSetProperty(p, EP_WinFunc); 1228 pWin->pOwner = p; 1229 if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){ 1230 sqlite3ErrorMsg(pParse, 1231 "DISTINCT is not supported for window functions" 1232 ); 1233 } 1234 }else{ 1235 sqlite3WindowDelete(pParse->db, pWin); 1236 } 1237 } 1238 1239 /* 1240 ** Possibly link window pWin into the list at pSel->pWin (window functions 1241 ** to be processed as part of SELECT statement pSel). The window is linked 1242 ** in if either (a) there are no other windows already linked to this 1243 ** SELECT, or (b) the windows already linked use a compatible window frame. 1244 */ 1245 void sqlite3WindowLink(Select *pSel, Window *pWin){ 1246 if( 0==pSel->pWin 1247 || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0) 1248 ){ 1249 pWin->pNextWin = pSel->pWin; 1250 if( pSel->pWin ){ 1251 pSel->pWin->ppThis = &pWin->pNextWin; 1252 } 1253 pSel->pWin = pWin; 1254 pWin->ppThis = &pSel->pWin; 1255 } 1256 } 1257 1258 /* 1259 ** Return 0 if the two window objects are identical, or non-zero otherwise. 1260 ** Identical window objects can be processed in a single scan. 1261 */ 1262 int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2, int bFilter){ 1263 if( p1->eFrmType!=p2->eFrmType ) return 1; 1264 if( p1->eStart!=p2->eStart ) return 1; 1265 if( p1->eEnd!=p2->eEnd ) return 1; 1266 if( p1->eExclude!=p2->eExclude ) return 1; 1267 if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1; 1268 if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1; 1269 if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1; 1270 if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1; 1271 if( bFilter ){ 1272 if( sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1) ) return 1; 1273 } 1274 return 0; 1275 } 1276 1277 1278 /* 1279 ** This is called by code in select.c before it calls sqlite3WhereBegin() 1280 ** to begin iterating through the sub-query results. It is used to allocate 1281 ** and initialize registers and cursors used by sqlite3WindowCodeStep(). 1282 */ 1283 void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){ 1284 Window *pWin; 1285 Vdbe *v = sqlite3GetVdbe(pParse); 1286 1287 /* Allocate registers to use for PARTITION BY values, if any. Initialize 1288 ** said registers to NULL. */ 1289 if( pMWin->pPartition ){ 1290 int nExpr = pMWin->pPartition->nExpr; 1291 pMWin->regPart = pParse->nMem+1; 1292 pParse->nMem += nExpr; 1293 sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1); 1294 } 1295 1296 pMWin->regOne = ++pParse->nMem; 1297 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne); 1298 1299 if( pMWin->eExclude ){ 1300 pMWin->regStartRowid = ++pParse->nMem; 1301 pMWin->regEndRowid = ++pParse->nMem; 1302 pMWin->csrApp = pParse->nTab++; 1303 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid); 1304 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid); 1305 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr); 1306 return; 1307 } 1308 1309 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1310 FuncDef *p = pWin->pFunc; 1311 if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){ 1312 /* The inline versions of min() and max() require a single ephemeral 1313 ** table and 3 registers. The registers are used as follows: 1314 ** 1315 ** regApp+0: slot to copy min()/max() argument to for MakeRecord 1316 ** regApp+1: integer value used to ensure keys are unique 1317 ** regApp+2: output of MakeRecord 1318 */ 1319 ExprList *pList = pWin->pOwner->x.pList; 1320 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0); 1321 pWin->csrApp = pParse->nTab++; 1322 pWin->regApp = pParse->nMem+1; 1323 pParse->nMem += 3; 1324 if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){ 1325 assert( pKeyInfo->aSortFlags[0]==0 ); 1326 pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC; 1327 } 1328 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2); 1329 sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO); 1330 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1); 1331 } 1332 else if( p->zName==nth_valueName || p->zName==first_valueName ){ 1333 /* Allocate two registers at pWin->regApp. These will be used to 1334 ** store the start and end index of the current frame. */ 1335 pWin->regApp = pParse->nMem+1; 1336 pWin->csrApp = pParse->nTab++; 1337 pParse->nMem += 2; 1338 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr); 1339 } 1340 else if( p->zName==leadName || p->zName==lagName ){ 1341 pWin->csrApp = pParse->nTab++; 1342 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr); 1343 } 1344 } 1345 } 1346 1347 #define WINDOW_STARTING_INT 0 1348 #define WINDOW_ENDING_INT 1 1349 #define WINDOW_NTH_VALUE_INT 2 1350 #define WINDOW_STARTING_NUM 3 1351 #define WINDOW_ENDING_NUM 4 1352 1353 /* 1354 ** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the 1355 ** value of the second argument to nth_value() (eCond==2) has just been 1356 ** evaluated and the result left in register reg. This function generates VM 1357 ** code to check that the value is a non-negative integer and throws an 1358 ** exception if it is not. 1359 */ 1360 static void windowCheckValue(Parse *pParse, int reg, int eCond){ 1361 static const char *azErr[] = { 1362 "frame starting offset must be a non-negative integer", 1363 "frame ending offset must be a non-negative integer", 1364 "second argument to nth_value must be a positive integer", 1365 "frame starting offset must be a non-negative number", 1366 "frame ending offset must be a non-negative number", 1367 }; 1368 static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge }; 1369 Vdbe *v = sqlite3GetVdbe(pParse); 1370 int regZero = sqlite3GetTempReg(pParse); 1371 assert( eCond>=0 && eCond<ArraySize(azErr) ); 1372 sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero); 1373 if( eCond>=WINDOW_STARTING_NUM ){ 1374 int regString = sqlite3GetTempReg(pParse); 1375 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC); 1376 sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg); 1377 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL); 1378 VdbeCoverage(v); 1379 assert( eCond==3 || eCond==4 ); 1380 VdbeCoverageIf(v, eCond==3); 1381 VdbeCoverageIf(v, eCond==4); 1382 }else{ 1383 sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2); 1384 VdbeCoverage(v); 1385 assert( eCond==0 || eCond==1 || eCond==2 ); 1386 VdbeCoverageIf(v, eCond==0); 1387 VdbeCoverageIf(v, eCond==1); 1388 VdbeCoverageIf(v, eCond==2); 1389 } 1390 sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg); 1391 VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */ 1392 VdbeCoverageNeverNullIf(v, eCond==1); /* the OP_MustBeInt */ 1393 VdbeCoverageNeverNullIf(v, eCond==2); 1394 VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */ 1395 VdbeCoverageNeverNullIf(v, eCond==4); /* the OP_Ge */ 1396 sqlite3MayAbort(pParse); 1397 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort); 1398 sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC); 1399 sqlite3ReleaseTempReg(pParse, regZero); 1400 } 1401 1402 /* 1403 ** Return the number of arguments passed to the window-function associated 1404 ** with the object passed as the only argument to this function. 1405 */ 1406 static int windowArgCount(Window *pWin){ 1407 ExprList *pList = pWin->pOwner->x.pList; 1408 return (pList ? pList->nExpr : 0); 1409 } 1410 1411 typedef struct WindowCodeArg WindowCodeArg; 1412 typedef struct WindowCsrAndReg WindowCsrAndReg; 1413 1414 /* 1415 ** See comments above struct WindowCodeArg. 1416 */ 1417 struct WindowCsrAndReg { 1418 int csr; /* Cursor number */ 1419 int reg; /* First in array of peer values */ 1420 }; 1421 1422 /* 1423 ** A single instance of this structure is allocated on the stack by 1424 ** sqlite3WindowCodeStep() and a pointer to it passed to the various helper 1425 ** routines. This is to reduce the number of arguments required by each 1426 ** helper function. 1427 ** 1428 ** regArg: 1429 ** Each window function requires an accumulator register (just as an 1430 ** ordinary aggregate function does). This variable is set to the first 1431 ** in an array of accumulator registers - one for each window function 1432 ** in the WindowCodeArg.pMWin list. 1433 ** 1434 ** eDelete: 1435 ** The window functions implementation sometimes caches the input rows 1436 ** that it processes in a temporary table. If it is not zero, this 1437 ** variable indicates when rows may be removed from the temp table (in 1438 ** order to reduce memory requirements - it would always be safe just 1439 ** to leave them there). Possible values for eDelete are: 1440 ** 1441 ** WINDOW_RETURN_ROW: 1442 ** An input row can be discarded after it is returned to the caller. 1443 ** 1444 ** WINDOW_AGGINVERSE: 1445 ** An input row can be discarded after the window functions xInverse() 1446 ** callbacks have been invoked in it. 1447 ** 1448 ** WINDOW_AGGSTEP: 1449 ** An input row can be discarded after the window functions xStep() 1450 ** callbacks have been invoked in it. 1451 ** 1452 ** start,current,end 1453 ** Consider a window-frame similar to the following: 1454 ** 1455 ** (ORDER BY a, b GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING) 1456 ** 1457 ** The windows functions implmentation caches the input rows in a temp 1458 ** table, sorted by "a, b" (it actually populates the cache lazily, and 1459 ** aggressively removes rows once they are no longer required, but that's 1460 ** a mere detail). It keeps three cursors open on the temp table. One 1461 ** (current) that points to the next row to return to the query engine 1462 ** once its window function values have been calculated. Another (end) 1463 ** points to the next row to call the xStep() method of each window function 1464 ** on (so that it is 2 groups ahead of current). And a third (start) that 1465 ** points to the next row to call the xInverse() method of each window 1466 ** function on. 1467 ** 1468 ** Each cursor (start, current and end) consists of a VDBE cursor 1469 ** (WindowCsrAndReg.csr) and an array of registers (starting at 1470 ** WindowCodeArg.reg) that always contains a copy of the peer values 1471 ** read from the corresponding cursor. 1472 ** 1473 ** Depending on the window-frame in question, all three cursors may not 1474 ** be required. In this case both WindowCodeArg.csr and reg are set to 1475 ** 0. 1476 */ 1477 struct WindowCodeArg { 1478 Parse *pParse; /* Parse context */ 1479 Window *pMWin; /* First in list of functions being processed */ 1480 Vdbe *pVdbe; /* VDBE object */ 1481 int addrGosub; /* OP_Gosub to this address to return one row */ 1482 int regGosub; /* Register used with OP_Gosub(addrGosub) */ 1483 int regArg; /* First in array of accumulator registers */ 1484 int eDelete; /* See above */ 1485 1486 WindowCsrAndReg start; 1487 WindowCsrAndReg current; 1488 WindowCsrAndReg end; 1489 }; 1490 1491 /* 1492 ** Generate VM code to read the window frames peer values from cursor csr into 1493 ** an array of registers starting at reg. 1494 */ 1495 static void windowReadPeerValues( 1496 WindowCodeArg *p, 1497 int csr, 1498 int reg 1499 ){ 1500 Window *pMWin = p->pMWin; 1501 ExprList *pOrderBy = pMWin->pOrderBy; 1502 if( pOrderBy ){ 1503 Vdbe *v = sqlite3GetVdbe(p->pParse); 1504 ExprList *pPart = pMWin->pPartition; 1505 int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0); 1506 int i; 1507 for(i=0; i<pOrderBy->nExpr; i++){ 1508 sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i); 1509 } 1510 } 1511 } 1512 1513 /* 1514 ** Generate VM code to invoke either xStep() (if bInverse is 0) or 1515 ** xInverse (if bInverse is non-zero) for each window function in the 1516 ** linked list starting at pMWin. Or, for built-in window functions 1517 ** that do not use the standard function API, generate the required 1518 ** inline VM code. 1519 ** 1520 ** If argument csr is greater than or equal to 0, then argument reg is 1521 ** the first register in an array of registers guaranteed to be large 1522 ** enough to hold the array of arguments for each function. In this case 1523 ** the arguments are extracted from the current row of csr into the 1524 ** array of registers before invoking OP_AggStep or OP_AggInverse 1525 ** 1526 ** Or, if csr is less than zero, then the array of registers at reg is 1527 ** already populated with all columns from the current row of the sub-query. 1528 ** 1529 ** If argument regPartSize is non-zero, then it is a register containing the 1530 ** number of rows in the current partition. 1531 */ 1532 static void windowAggStep( 1533 WindowCodeArg *p, 1534 Window *pMWin, /* Linked list of window functions */ 1535 int csr, /* Read arguments from this cursor */ 1536 int bInverse, /* True to invoke xInverse instead of xStep */ 1537 int reg /* Array of registers */ 1538 ){ 1539 Parse *pParse = p->pParse; 1540 Vdbe *v = sqlite3GetVdbe(pParse); 1541 Window *pWin; 1542 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1543 FuncDef *pFunc = pWin->pFunc; 1544 int regArg; 1545 int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin); 1546 int i; 1547 1548 assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED ); 1549 1550 /* All OVER clauses in the same window function aggregate step must 1551 ** be the same. */ 1552 assert( pWin==pMWin || sqlite3WindowCompare(pParse,pWin,pMWin,0)==0 ); 1553 1554 for(i=0; i<nArg; i++){ 1555 if( i!=1 || pFunc->zName!=nth_valueName ){ 1556 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i); 1557 }else{ 1558 sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i); 1559 } 1560 } 1561 regArg = reg; 1562 1563 if( pMWin->regStartRowid==0 1564 && (pFunc->funcFlags & SQLITE_FUNC_MINMAX) 1565 && (pWin->eStart!=TK_UNBOUNDED) 1566 ){ 1567 int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg); 1568 VdbeCoverage(v); 1569 if( bInverse==0 ){ 1570 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1); 1571 sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp); 1572 sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2); 1573 sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2); 1574 }else{ 1575 sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1); 1576 VdbeCoverageNeverTaken(v); 1577 sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp); 1578 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); 1579 } 1580 sqlite3VdbeJumpHere(v, addrIsNull); 1581 }else if( pWin->regApp ){ 1582 assert( pFunc->zName==nth_valueName 1583 || pFunc->zName==first_valueName 1584 ); 1585 assert( bInverse==0 || bInverse==1 ); 1586 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1); 1587 }else if( pFunc->xSFunc!=noopStepFunc ){ 1588 int addrIf = 0; 1589 if( pWin->pFilter ){ 1590 int regTmp; 1591 assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr ); 1592 assert( pWin->bExprArgs || nArg ||pWin->pOwner->x.pList==0 ); 1593 regTmp = sqlite3GetTempReg(pParse); 1594 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp); 1595 addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1); 1596 VdbeCoverage(v); 1597 sqlite3ReleaseTempReg(pParse, regTmp); 1598 } 1599 1600 if( pWin->bExprArgs ){ 1601 int iStart = sqlite3VdbeCurrentAddr(v); 1602 VdbeOp *pOp, *pEnd; 1603 1604 nArg = pWin->pOwner->x.pList->nExpr; 1605 regArg = sqlite3GetTempRange(pParse, nArg); 1606 sqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0); 1607 1608 pEnd = sqlite3VdbeGetOp(v, -1); 1609 for(pOp=sqlite3VdbeGetOp(v, iStart); pOp<=pEnd; pOp++){ 1610 if( pOp->opcode==OP_Column && pOp->p1==pWin->iEphCsr ){ 1611 pOp->p1 = csr; 1612 } 1613 } 1614 } 1615 if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ 1616 CollSeq *pColl; 1617 assert( nArg>0 ); 1618 pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr); 1619 sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ); 1620 } 1621 sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep, 1622 bInverse, regArg, pWin->regAccum); 1623 sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF); 1624 sqlite3VdbeChangeP5(v, (u8)nArg); 1625 if( pWin->bExprArgs ){ 1626 sqlite3ReleaseTempRange(pParse, regArg, nArg); 1627 } 1628 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf); 1629 } 1630 } 1631 } 1632 1633 /* 1634 ** Values that may be passed as the second argument to windowCodeOp(). 1635 */ 1636 #define WINDOW_RETURN_ROW 1 1637 #define WINDOW_AGGINVERSE 2 1638 #define WINDOW_AGGSTEP 3 1639 1640 /* 1641 ** Generate VM code to invoke either xValue() (bFin==0) or xFinalize() 1642 ** (bFin==1) for each window function in the linked list starting at 1643 ** pMWin. Or, for built-in window-functions that do not use the standard 1644 ** API, generate the equivalent VM code. 1645 */ 1646 static void windowAggFinal(WindowCodeArg *p, int bFin){ 1647 Parse *pParse = p->pParse; 1648 Window *pMWin = p->pMWin; 1649 Vdbe *v = sqlite3GetVdbe(pParse); 1650 Window *pWin; 1651 1652 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1653 if( pMWin->regStartRowid==0 1654 && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX) 1655 && (pWin->eStart!=TK_UNBOUNDED) 1656 ){ 1657 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult); 1658 sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp); 1659 VdbeCoverage(v); 1660 sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult); 1661 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); 1662 }else if( pWin->regApp ){ 1663 assert( pMWin->regStartRowid==0 ); 1664 }else{ 1665 int nArg = windowArgCount(pWin); 1666 if( bFin ){ 1667 sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg); 1668 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF); 1669 sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult); 1670 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); 1671 }else{ 1672 sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult); 1673 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF); 1674 } 1675 } 1676 } 1677 } 1678 1679 /* 1680 ** Generate code to calculate the current values of all window functions in the 1681 ** p->pMWin list by doing a full scan of the current window frame. Store the 1682 ** results in the Window.regResult registers, ready to return the upper 1683 ** layer. 1684 */ 1685 static void windowFullScan(WindowCodeArg *p){ 1686 Window *pWin; 1687 Parse *pParse = p->pParse; 1688 Window *pMWin = p->pMWin; 1689 Vdbe *v = p->pVdbe; 1690 1691 int regCRowid = 0; /* Current rowid value */ 1692 int regCPeer = 0; /* Current peer values */ 1693 int regRowid = 0; /* AggStep rowid value */ 1694 int regPeer = 0; /* AggStep peer values */ 1695 1696 int nPeer; 1697 int lblNext; 1698 int lblBrk; 1699 int addrNext; 1700 int csr; 1701 1702 VdbeModuleComment((v, "windowFullScan begin")); 1703 1704 assert( pMWin!=0 ); 1705 csr = pMWin->csrApp; 1706 nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0); 1707 1708 lblNext = sqlite3VdbeMakeLabel(pParse); 1709 lblBrk = sqlite3VdbeMakeLabel(pParse); 1710 1711 regCRowid = sqlite3GetTempReg(pParse); 1712 regRowid = sqlite3GetTempReg(pParse); 1713 if( nPeer ){ 1714 regCPeer = sqlite3GetTempRange(pParse, nPeer); 1715 regPeer = sqlite3GetTempRange(pParse, nPeer); 1716 } 1717 1718 sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid); 1719 windowReadPeerValues(p, pMWin->iEphCsr, regCPeer); 1720 1721 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1722 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); 1723 } 1724 1725 sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid); 1726 VdbeCoverage(v); 1727 addrNext = sqlite3VdbeCurrentAddr(v); 1728 sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid); 1729 sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid); 1730 VdbeCoverageNeverNull(v); 1731 1732 if( pMWin->eExclude==TK_CURRENT ){ 1733 sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid); 1734 VdbeCoverageNeverNull(v); 1735 }else if( pMWin->eExclude!=TK_NO ){ 1736 int addr; 1737 int addrEq = 0; 1738 KeyInfo *pKeyInfo = 0; 1739 1740 if( pMWin->pOrderBy ){ 1741 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0); 1742 } 1743 if( pMWin->eExclude==TK_TIES ){ 1744 addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid); 1745 VdbeCoverageNeverNull(v); 1746 } 1747 if( pKeyInfo ){ 1748 windowReadPeerValues(p, csr, regPeer); 1749 sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer); 1750 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO); 1751 addr = sqlite3VdbeCurrentAddr(v)+1; 1752 sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr); 1753 VdbeCoverageEqNe(v); 1754 }else{ 1755 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext); 1756 } 1757 if( addrEq ) sqlite3VdbeJumpHere(v, addrEq); 1758 } 1759 1760 windowAggStep(p, pMWin, csr, 0, p->regArg); 1761 1762 sqlite3VdbeResolveLabel(v, lblNext); 1763 sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext); 1764 VdbeCoverage(v); 1765 sqlite3VdbeJumpHere(v, addrNext-1); 1766 sqlite3VdbeJumpHere(v, addrNext+1); 1767 sqlite3ReleaseTempReg(pParse, regRowid); 1768 sqlite3ReleaseTempReg(pParse, regCRowid); 1769 if( nPeer ){ 1770 sqlite3ReleaseTempRange(pParse, regPeer, nPeer); 1771 sqlite3ReleaseTempRange(pParse, regCPeer, nPeer); 1772 } 1773 1774 windowAggFinal(p, 1); 1775 VdbeModuleComment((v, "windowFullScan end")); 1776 } 1777 1778 /* 1779 ** Invoke the sub-routine at regGosub (generated by code in select.c) to 1780 ** return the current row of Window.iEphCsr. If all window functions are 1781 ** aggregate window functions that use the standard API, a single 1782 ** OP_Gosub instruction is all that this routine generates. Extra VM code 1783 ** for per-row processing is only generated for the following built-in window 1784 ** functions: 1785 ** 1786 ** nth_value() 1787 ** first_value() 1788 ** lag() 1789 ** lead() 1790 */ 1791 static void windowReturnOneRow(WindowCodeArg *p){ 1792 Window *pMWin = p->pMWin; 1793 Vdbe *v = p->pVdbe; 1794 1795 if( pMWin->regStartRowid ){ 1796 windowFullScan(p); 1797 }else{ 1798 Parse *pParse = p->pParse; 1799 Window *pWin; 1800 1801 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1802 FuncDef *pFunc = pWin->pFunc; 1803 if( pFunc->zName==nth_valueName 1804 || pFunc->zName==first_valueName 1805 ){ 1806 int csr = pWin->csrApp; 1807 int lbl = sqlite3VdbeMakeLabel(pParse); 1808 int tmpReg = sqlite3GetTempReg(pParse); 1809 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult); 1810 1811 if( pFunc->zName==nth_valueName ){ 1812 sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg); 1813 windowCheckValue(pParse, tmpReg, 2); 1814 }else{ 1815 sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg); 1816 } 1817 sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg); 1818 sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg); 1819 VdbeCoverageNeverNull(v); 1820 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg); 1821 VdbeCoverageNeverTaken(v); 1822 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult); 1823 sqlite3VdbeResolveLabel(v, lbl); 1824 sqlite3ReleaseTempReg(pParse, tmpReg); 1825 } 1826 else if( pFunc->zName==leadName || pFunc->zName==lagName ){ 1827 int nArg = pWin->pOwner->x.pList->nExpr; 1828 int csr = pWin->csrApp; 1829 int lbl = sqlite3VdbeMakeLabel(pParse); 1830 int tmpReg = sqlite3GetTempReg(pParse); 1831 int iEph = pMWin->iEphCsr; 1832 1833 if( nArg<3 ){ 1834 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult); 1835 }else{ 1836 sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult); 1837 } 1838 sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg); 1839 if( nArg<2 ){ 1840 int val = (pFunc->zName==leadName ? 1 : -1); 1841 sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val); 1842 }else{ 1843 int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract); 1844 int tmpReg2 = sqlite3GetTempReg(pParse); 1845 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2); 1846 sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg); 1847 sqlite3ReleaseTempReg(pParse, tmpReg2); 1848 } 1849 1850 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg); 1851 VdbeCoverage(v); 1852 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult); 1853 sqlite3VdbeResolveLabel(v, lbl); 1854 sqlite3ReleaseTempReg(pParse, tmpReg); 1855 } 1856 } 1857 } 1858 sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub); 1859 } 1860 1861 /* 1862 ** Generate code to set the accumulator register for each window function 1863 ** in the linked list passed as the second argument to NULL. And perform 1864 ** any equivalent initialization required by any built-in window functions 1865 ** in the list. 1866 */ 1867 static int windowInitAccum(Parse *pParse, Window *pMWin){ 1868 Vdbe *v = sqlite3GetVdbe(pParse); 1869 int regArg; 1870 int nArg = 0; 1871 Window *pWin; 1872 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1873 FuncDef *pFunc = pWin->pFunc; 1874 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); 1875 nArg = MAX(nArg, windowArgCount(pWin)); 1876 if( pMWin->regStartRowid==0 ){ 1877 if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){ 1878 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp); 1879 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1); 1880 } 1881 1882 if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){ 1883 assert( pWin->eStart!=TK_UNBOUNDED ); 1884 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp); 1885 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1); 1886 } 1887 } 1888 } 1889 regArg = pParse->nMem+1; 1890 pParse->nMem += nArg; 1891 return regArg; 1892 } 1893 1894 /* 1895 ** Return true if the current frame should be cached in the ephemeral table, 1896 ** even if there are no xInverse() calls required. 1897 */ 1898 static int windowCacheFrame(Window *pMWin){ 1899 Window *pWin; 1900 if( pMWin->regStartRowid ) return 1; 1901 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1902 FuncDef *pFunc = pWin->pFunc; 1903 if( (pFunc->zName==nth_valueName) 1904 || (pFunc->zName==first_valueName) 1905 || (pFunc->zName==leadName) 1906 || (pFunc->zName==lagName) 1907 ){ 1908 return 1; 1909 } 1910 } 1911 return 0; 1912 } 1913 1914 /* 1915 ** regOld and regNew are each the first register in an array of size 1916 ** pOrderBy->nExpr. This function generates code to compare the two 1917 ** arrays of registers using the collation sequences and other comparison 1918 ** parameters specified by pOrderBy. 1919 ** 1920 ** If the two arrays are not equal, the contents of regNew is copied to 1921 ** regOld and control falls through. Otherwise, if the contents of the arrays 1922 ** are equal, an OP_Goto is executed. The address of the OP_Goto is returned. 1923 */ 1924 static void windowIfNewPeer( 1925 Parse *pParse, 1926 ExprList *pOrderBy, 1927 int regNew, /* First in array of new values */ 1928 int regOld, /* First in array of old values */ 1929 int addr /* Jump here */ 1930 ){ 1931 Vdbe *v = sqlite3GetVdbe(pParse); 1932 if( pOrderBy ){ 1933 int nVal = pOrderBy->nExpr; 1934 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0); 1935 sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal); 1936 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO); 1937 sqlite3VdbeAddOp3(v, OP_Jump, 1938 sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1 1939 ); 1940 VdbeCoverageEqNe(v); 1941 sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1); 1942 }else{ 1943 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); 1944 } 1945 } 1946 1947 /* 1948 ** This function is called as part of generating VM programs for RANGE 1949 ** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for 1950 ** the ORDER BY term in the window, and that argument op is OP_Ge, it generates 1951 ** code equivalent to: 1952 ** 1953 ** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl; 1954 ** 1955 ** The value of parameter op may also be OP_Gt or OP_Le. In these cases the 1956 ** operator in the above pseudo-code is replaced with ">" or "<=", respectively. 1957 ** 1958 ** If the sort-order for the ORDER BY term in the window is DESC, then the 1959 ** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is 1960 ** subtracted. And the comparison operator is inverted to - ">=" becomes "<=", 1961 ** ">" becomes "<", and so on. So, with DESC sort order, if the argument op 1962 ** is OP_Ge, the generated code is equivalent to: 1963 ** 1964 ** if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl; 1965 ** 1966 ** A special type of arithmetic is used such that if csr1.peerVal is not 1967 ** a numeric type (real or integer), then the result of the addition addition 1968 ** or subtraction is a a copy of csr1.peerVal. 1969 */ 1970 static void windowCodeRangeTest( 1971 WindowCodeArg *p, 1972 int op, /* OP_Ge, OP_Gt, or OP_Le */ 1973 int csr1, /* Cursor number for cursor 1 */ 1974 int regVal, /* Register containing non-negative number */ 1975 int csr2, /* Cursor number for cursor 2 */ 1976 int lbl /* Jump destination if condition is true */ 1977 ){ 1978 Parse *pParse = p->pParse; 1979 Vdbe *v = sqlite3GetVdbe(pParse); 1980 ExprList *pOrderBy = p->pMWin->pOrderBy; /* ORDER BY clause for window */ 1981 int reg1 = sqlite3GetTempReg(pParse); /* Reg. for csr1.peerVal+regVal */ 1982 int reg2 = sqlite3GetTempReg(pParse); /* Reg. for csr2.peerVal */ 1983 int regString = ++pParse->nMem; /* Reg. for constant value '' */ 1984 int arith = OP_Add; /* OP_Add or OP_Subtract */ 1985 int addrGe; /* Jump destination */ 1986 1987 assert( op==OP_Ge || op==OP_Gt || op==OP_Le ); 1988 assert( pOrderBy && pOrderBy->nExpr==1 ); 1989 if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_DESC ){ 1990 switch( op ){ 1991 case OP_Ge: op = OP_Le; break; 1992 case OP_Gt: op = OP_Lt; break; 1993 default: assert( op==OP_Le ); op = OP_Ge; break; 1994 } 1995 arith = OP_Subtract; 1996 } 1997 1998 /* Read the peer-value from each cursor into a register */ 1999 windowReadPeerValues(p, csr1, reg1); 2000 windowReadPeerValues(p, csr2, reg2); 2001 2002 VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl", 2003 reg1, (arith==OP_Add ? "+" : "-"), regVal, 2004 ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2 2005 )); 2006 2007 /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1). 2008 ** This block adds (or subtracts for DESC) the numeric value in regVal 2009 ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob), 2010 ** then leave reg1 as it is. In pseudo-code, this is implemented as: 2011 ** 2012 ** if( reg1>='' ) goto addrGe; 2013 ** reg1 = reg1 +/- regVal 2014 ** addrGe: 2015 ** 2016 ** Since all strings and blobs are greater-than-or-equal-to an empty string, 2017 ** the add/subtract is skipped for these, as required. If reg1 is a NULL, 2018 ** then the arithmetic is performed, but since adding or subtracting from 2019 ** NULL is always NULL anyway, this case is handled as required too. */ 2020 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC); 2021 addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1); 2022 VdbeCoverage(v); 2023 sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1); 2024 sqlite3VdbeJumpHere(v, addrGe); 2025 2026 /* If the BIGNULL flag is set for the ORDER BY, then it is required to 2027 ** consider NULL values to be larger than all other values, instead of 2028 ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this 2029 ** (and adding that capability causes a performance regression), so 2030 ** instead if the BIGNULL flag is set then cases where either reg1 or 2031 ** reg2 are NULL are handled separately in the following block. The code 2032 ** generated is equivalent to: 2033 ** 2034 ** if( reg1 IS NULL ){ 2035 ** if( op==OP_Ge ) goto lbl; 2036 ** if( op==OP_Gt && reg2 IS NOT NULL ) goto lbl; 2037 ** if( op==OP_Le && reg2 IS NULL ) goto lbl; 2038 ** }else if( reg2 IS NULL ){ 2039 ** if( op==OP_Le ) goto lbl; 2040 ** } 2041 ** 2042 ** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is 2043 ** not taken, control jumps over the comparison operator coded below this 2044 ** block. */ 2045 if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_BIGNULL ){ 2046 /* This block runs if reg1 contains a NULL. */ 2047 int addr = sqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v); 2048 switch( op ){ 2049 case OP_Ge: 2050 sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl); 2051 break; 2052 case OP_Gt: 2053 sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl); 2054 VdbeCoverage(v); 2055 break; 2056 case OP_Le: 2057 sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); 2058 VdbeCoverage(v); 2059 break; 2060 default: assert( op==OP_Lt ); /* no-op */ break; 2061 } 2062 sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3); 2063 2064 /* This block runs if reg1 is not NULL, but reg2 is. */ 2065 sqlite3VdbeJumpHere(v, addr); 2066 sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); VdbeCoverage(v); 2067 if( op==OP_Gt || op==OP_Ge ){ 2068 sqlite3VdbeChangeP2(v, -1, sqlite3VdbeCurrentAddr(v)+1); 2069 } 2070 } 2071 2072 /* Compare registers reg2 and reg1, taking the jump if required. Note that 2073 ** control skips over this test if the BIGNULL flag is set and either 2074 ** reg1 or reg2 contain a NULL value. */ 2075 sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v); 2076 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); 2077 2078 assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le ); 2079 testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge); 2080 testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt); 2081 testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le); 2082 testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt); 2083 sqlite3ReleaseTempReg(pParse, reg1); 2084 sqlite3ReleaseTempReg(pParse, reg2); 2085 2086 VdbeModuleComment((v, "CodeRangeTest: end")); 2087 } 2088 2089 /* 2090 ** Helper function for sqlite3WindowCodeStep(). Each call to this function 2091 ** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE 2092 ** operation. Refer to the header comment for sqlite3WindowCodeStep() for 2093 ** details. 2094 */ 2095 static int windowCodeOp( 2096 WindowCodeArg *p, /* Context object */ 2097 int op, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */ 2098 int regCountdown, /* Register for OP_IfPos countdown */ 2099 int jumpOnEof /* Jump here if stepped cursor reaches EOF */ 2100 ){ 2101 int csr, reg; 2102 Parse *pParse = p->pParse; 2103 Window *pMWin = p->pMWin; 2104 int ret = 0; 2105 Vdbe *v = p->pVdbe; 2106 int addrContinue = 0; 2107 int bPeer = (pMWin->eFrmType!=TK_ROWS); 2108 2109 int lblDone = sqlite3VdbeMakeLabel(pParse); 2110 int addrNextRange = 0; 2111 2112 /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame 2113 ** starts with UNBOUNDED PRECEDING. */ 2114 if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){ 2115 assert( regCountdown==0 && jumpOnEof==0 ); 2116 return 0; 2117 } 2118 2119 if( regCountdown>0 ){ 2120 if( pMWin->eFrmType==TK_RANGE ){ 2121 addrNextRange = sqlite3VdbeCurrentAddr(v); 2122 assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP ); 2123 if( op==WINDOW_AGGINVERSE ){ 2124 if( pMWin->eStart==TK_FOLLOWING ){ 2125 windowCodeRangeTest( 2126 p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone 2127 ); 2128 }else{ 2129 windowCodeRangeTest( 2130 p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone 2131 ); 2132 } 2133 }else{ 2134 windowCodeRangeTest( 2135 p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone 2136 ); 2137 } 2138 }else{ 2139 sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, lblDone, 1); 2140 VdbeCoverage(v); 2141 } 2142 } 2143 2144 if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){ 2145 windowAggFinal(p, 0); 2146 } 2147 addrContinue = sqlite3VdbeCurrentAddr(v); 2148 2149 /* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or 2150 ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the 2151 ** start cursor does not advance past the end cursor within the 2152 ** temporary table. It otherwise might, if (a>b). */ 2153 if( pMWin->eStart==pMWin->eEnd && regCountdown 2154 && pMWin->eFrmType==TK_RANGE && op==WINDOW_AGGINVERSE 2155 ){ 2156 int regRowid1 = sqlite3GetTempReg(pParse); 2157 int regRowid2 = sqlite3GetTempReg(pParse); 2158 sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1); 2159 sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2); 2160 sqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1); 2161 VdbeCoverage(v); 2162 sqlite3ReleaseTempReg(pParse, regRowid1); 2163 sqlite3ReleaseTempReg(pParse, regRowid2); 2164 assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ); 2165 } 2166 2167 switch( op ){ 2168 case WINDOW_RETURN_ROW: 2169 csr = p->current.csr; 2170 reg = p->current.reg; 2171 windowReturnOneRow(p); 2172 break; 2173 2174 case WINDOW_AGGINVERSE: 2175 csr = p->start.csr; 2176 reg = p->start.reg; 2177 if( pMWin->regStartRowid ){ 2178 assert( pMWin->regEndRowid ); 2179 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1); 2180 }else{ 2181 windowAggStep(p, pMWin, csr, 1, p->regArg); 2182 } 2183 break; 2184 2185 default: 2186 assert( op==WINDOW_AGGSTEP ); 2187 csr = p->end.csr; 2188 reg = p->end.reg; 2189 if( pMWin->regStartRowid ){ 2190 assert( pMWin->regEndRowid ); 2191 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1); 2192 }else{ 2193 windowAggStep(p, pMWin, csr, 0, p->regArg); 2194 } 2195 break; 2196 } 2197 2198 if( op==p->eDelete ){ 2199 sqlite3VdbeAddOp1(v, OP_Delete, csr); 2200 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION); 2201 } 2202 2203 if( jumpOnEof ){ 2204 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2); 2205 VdbeCoverage(v); 2206 ret = sqlite3VdbeAddOp0(v, OP_Goto); 2207 }else{ 2208 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer); 2209 VdbeCoverage(v); 2210 if( bPeer ){ 2211 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblDone); 2212 } 2213 } 2214 2215 if( bPeer ){ 2216 int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0); 2217 int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0); 2218 windowReadPeerValues(p, csr, regTmp); 2219 windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue); 2220 sqlite3ReleaseTempRange(pParse, regTmp, nReg); 2221 } 2222 2223 if( addrNextRange ){ 2224 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange); 2225 } 2226 sqlite3VdbeResolveLabel(v, lblDone); 2227 return ret; 2228 } 2229 2230 2231 /* 2232 ** Allocate and return a duplicate of the Window object indicated by the 2233 ** third argument. Set the Window.pOwner field of the new object to 2234 ** pOwner. 2235 */ 2236 Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){ 2237 Window *pNew = 0; 2238 if( ALWAYS(p) ){ 2239 pNew = sqlite3DbMallocZero(db, sizeof(Window)); 2240 if( pNew ){ 2241 pNew->zName = sqlite3DbStrDup(db, p->zName); 2242 pNew->zBase = sqlite3DbStrDup(db, p->zBase); 2243 pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0); 2244 pNew->pFunc = p->pFunc; 2245 pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0); 2246 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0); 2247 pNew->eFrmType = p->eFrmType; 2248 pNew->eEnd = p->eEnd; 2249 pNew->eStart = p->eStart; 2250 pNew->eExclude = p->eExclude; 2251 pNew->regResult = p->regResult; 2252 pNew->pStart = sqlite3ExprDup(db, p->pStart, 0); 2253 pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0); 2254 pNew->pOwner = pOwner; 2255 pNew->bImplicitFrame = p->bImplicitFrame; 2256 } 2257 } 2258 return pNew; 2259 } 2260 2261 /* 2262 ** Return a copy of the linked list of Window objects passed as the 2263 ** second argument. 2264 */ 2265 Window *sqlite3WindowListDup(sqlite3 *db, Window *p){ 2266 Window *pWin; 2267 Window *pRet = 0; 2268 Window **pp = &pRet; 2269 2270 for(pWin=p; pWin; pWin=pWin->pNextWin){ 2271 *pp = sqlite3WindowDup(db, 0, pWin); 2272 if( *pp==0 ) break; 2273 pp = &((*pp)->pNextWin); 2274 } 2275 2276 return pRet; 2277 } 2278 2279 /* 2280 ** Return true if it can be determined at compile time that expression 2281 ** pExpr evaluates to a value that, when cast to an integer, is greater 2282 ** than zero. False otherwise. 2283 ** 2284 ** If an OOM error occurs, this function sets the Parse.db.mallocFailed 2285 ** flag and returns zero. 2286 */ 2287 static int windowExprGtZero(Parse *pParse, Expr *pExpr){ 2288 int ret = 0; 2289 sqlite3 *db = pParse->db; 2290 sqlite3_value *pVal = 0; 2291 sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal); 2292 if( pVal && sqlite3_value_int(pVal)>0 ){ 2293 ret = 1; 2294 } 2295 sqlite3ValueFree(pVal); 2296 return ret; 2297 } 2298 2299 /* 2300 ** sqlite3WhereBegin() has already been called for the SELECT statement 2301 ** passed as the second argument when this function is invoked. It generates 2302 ** code to populate the Window.regResult register for each window function 2303 ** and invoke the sub-routine at instruction addrGosub once for each row. 2304 ** sqlite3WhereEnd() is always called before returning. 2305 ** 2306 ** This function handles several different types of window frames, which 2307 ** require slightly different processing. The following pseudo code is 2308 ** used to implement window frames of the form: 2309 ** 2310 ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING 2311 ** 2312 ** Other window frame types use variants of the following: 2313 ** 2314 ** ... loop started by sqlite3WhereBegin() ... 2315 ** if( new partition ){ 2316 ** Gosub flush 2317 ** } 2318 ** Insert new row into eph table. 2319 ** 2320 ** if( first row of partition ){ 2321 ** // Rewind three cursors, all open on the eph table. 2322 ** Rewind(csrEnd); 2323 ** Rewind(csrStart); 2324 ** Rewind(csrCurrent); 2325 ** 2326 ** regEnd = <expr2> // FOLLOWING expression 2327 ** regStart = <expr1> // PRECEDING expression 2328 ** }else{ 2329 ** // First time this branch is taken, the eph table contains two 2330 ** // rows. The first row in the partition, which all three cursors 2331 ** // currently point to, and the following row. 2332 ** AGGSTEP 2333 ** if( (regEnd--)<=0 ){ 2334 ** RETURN_ROW 2335 ** if( (regStart--)<=0 ){ 2336 ** AGGINVERSE 2337 ** } 2338 ** } 2339 ** } 2340 ** } 2341 ** flush: 2342 ** AGGSTEP 2343 ** while( 1 ){ 2344 ** RETURN ROW 2345 ** if( csrCurrent is EOF ) break; 2346 ** if( (regStart--)<=0 ){ 2347 ** AggInverse(csrStart) 2348 ** Next(csrStart) 2349 ** } 2350 ** } 2351 ** 2352 ** The pseudo-code above uses the following shorthand: 2353 ** 2354 ** AGGSTEP: invoke the aggregate xStep() function for each window function 2355 ** with arguments read from the current row of cursor csrEnd, then 2356 ** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()). 2357 ** 2358 ** RETURN_ROW: return a row to the caller based on the contents of the 2359 ** current row of csrCurrent and the current state of all 2360 ** aggregates. Then step cursor csrCurrent forward one row. 2361 ** 2362 ** AGGINVERSE: invoke the aggregate xInverse() function for each window 2363 ** functions with arguments read from the current row of cursor 2364 ** csrStart. Then step csrStart forward one row. 2365 ** 2366 ** There are two other ROWS window frames that are handled significantly 2367 ** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING" 2368 ** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special 2369 ** cases because they change the order in which the three cursors (csrStart, 2370 ** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that 2371 ** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these 2372 ** three. 2373 ** 2374 ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING 2375 ** 2376 ** ... loop started by sqlite3WhereBegin() ... 2377 ** if( new partition ){ 2378 ** Gosub flush 2379 ** } 2380 ** Insert new row into eph table. 2381 ** if( first row of partition ){ 2382 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) 2383 ** regEnd = <expr2> 2384 ** regStart = <expr1> 2385 ** }else{ 2386 ** if( (regEnd--)<=0 ){ 2387 ** AGGSTEP 2388 ** } 2389 ** RETURN_ROW 2390 ** if( (regStart--)<=0 ){ 2391 ** AGGINVERSE 2392 ** } 2393 ** } 2394 ** } 2395 ** flush: 2396 ** if( (regEnd--)<=0 ){ 2397 ** AGGSTEP 2398 ** } 2399 ** RETURN_ROW 2400 ** 2401 ** 2402 ** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING 2403 ** 2404 ** ... loop started by sqlite3WhereBegin() ... 2405 ** if( new partition ){ 2406 ** Gosub flush 2407 ** } 2408 ** Insert new row into eph table. 2409 ** if( first row of partition ){ 2410 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) 2411 ** regEnd = <expr2> 2412 ** regStart = regEnd - <expr1> 2413 ** }else{ 2414 ** AGGSTEP 2415 ** if( (regEnd--)<=0 ){ 2416 ** RETURN_ROW 2417 ** } 2418 ** if( (regStart--)<=0 ){ 2419 ** AGGINVERSE 2420 ** } 2421 ** } 2422 ** } 2423 ** flush: 2424 ** AGGSTEP 2425 ** while( 1 ){ 2426 ** if( (regEnd--)<=0 ){ 2427 ** RETURN_ROW 2428 ** if( eof ) break; 2429 ** } 2430 ** if( (regStart--)<=0 ){ 2431 ** AGGINVERSE 2432 ** if( eof ) break 2433 ** } 2434 ** } 2435 ** while( !eof csrCurrent ){ 2436 ** RETURN_ROW 2437 ** } 2438 ** 2439 ** For the most part, the patterns above are adapted to support UNBOUNDED by 2440 ** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and 2441 ** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING". 2442 ** This is optimized of course - branches that will never be taken and 2443 ** conditions that are always true are omitted from the VM code. The only 2444 ** exceptional case is: 2445 ** 2446 ** ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING 2447 ** 2448 ** ... loop started by sqlite3WhereBegin() ... 2449 ** if( new partition ){ 2450 ** Gosub flush 2451 ** } 2452 ** Insert new row into eph table. 2453 ** if( first row of partition ){ 2454 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) 2455 ** regStart = <expr1> 2456 ** }else{ 2457 ** AGGSTEP 2458 ** } 2459 ** } 2460 ** flush: 2461 ** AGGSTEP 2462 ** while( 1 ){ 2463 ** if( (regStart--)<=0 ){ 2464 ** AGGINVERSE 2465 ** if( eof ) break 2466 ** } 2467 ** RETURN_ROW 2468 ** } 2469 ** while( !eof csrCurrent ){ 2470 ** RETURN_ROW 2471 ** } 2472 ** 2473 ** Also requiring special handling are the cases: 2474 ** 2475 ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING 2476 ** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING 2477 ** 2478 ** when (expr1 < expr2). This is detected at runtime, not by this function. 2479 ** To handle this case, the pseudo-code programs depicted above are modified 2480 ** slightly to be: 2481 ** 2482 ** ... loop started by sqlite3WhereBegin() ... 2483 ** if( new partition ){ 2484 ** Gosub flush 2485 ** } 2486 ** Insert new row into eph table. 2487 ** if( first row of partition ){ 2488 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) 2489 ** regEnd = <expr2> 2490 ** regStart = <expr1> 2491 ** if( regEnd < regStart ){ 2492 ** RETURN_ROW 2493 ** delete eph table contents 2494 ** continue 2495 ** } 2496 ** ... 2497 ** 2498 ** The new "continue" statement in the above jumps to the next iteration 2499 ** of the outer loop - the one started by sqlite3WhereBegin(). 2500 ** 2501 ** The various GROUPS cases are implemented using the same patterns as 2502 ** ROWS. The VM code is modified slightly so that: 2503 ** 2504 ** 1. The else branch in the main loop is only taken if the row just 2505 ** added to the ephemeral table is the start of a new group. In 2506 ** other words, it becomes: 2507 ** 2508 ** ... loop started by sqlite3WhereBegin() ... 2509 ** if( new partition ){ 2510 ** Gosub flush 2511 ** } 2512 ** Insert new row into eph table. 2513 ** if( first row of partition ){ 2514 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) 2515 ** regEnd = <expr2> 2516 ** regStart = <expr1> 2517 ** }else if( new group ){ 2518 ** ... 2519 ** } 2520 ** } 2521 ** 2522 ** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or 2523 ** AGGINVERSE step processes the current row of the relevant cursor and 2524 ** all subsequent rows belonging to the same group. 2525 ** 2526 ** RANGE window frames are a little different again. As for GROUPS, the 2527 ** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE 2528 ** deal in groups instead of rows. As for ROWS and GROUPS, there are three 2529 ** basic cases: 2530 ** 2531 ** RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING 2532 ** 2533 ** ... loop started by sqlite3WhereBegin() ... 2534 ** if( new partition ){ 2535 ** Gosub flush 2536 ** } 2537 ** Insert new row into eph table. 2538 ** if( first row of partition ){ 2539 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) 2540 ** regEnd = <expr2> 2541 ** regStart = <expr1> 2542 ** }else{ 2543 ** AGGSTEP 2544 ** while( (csrCurrent.key + regEnd) < csrEnd.key ){ 2545 ** RETURN_ROW 2546 ** while( csrStart.key + regStart) < csrCurrent.key ){ 2547 ** AGGINVERSE 2548 ** } 2549 ** } 2550 ** } 2551 ** } 2552 ** flush: 2553 ** AGGSTEP 2554 ** while( 1 ){ 2555 ** RETURN ROW 2556 ** if( csrCurrent is EOF ) break; 2557 ** while( csrStart.key + regStart) < csrCurrent.key ){ 2558 ** AGGINVERSE 2559 ** } 2560 ** } 2561 ** } 2562 ** 2563 ** In the above notation, "csr.key" means the current value of the ORDER BY 2564 ** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING 2565 ** or <expr PRECEDING) read from cursor csr. 2566 ** 2567 ** RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING 2568 ** 2569 ** ... loop started by sqlite3WhereBegin() ... 2570 ** if( new partition ){ 2571 ** Gosub flush 2572 ** } 2573 ** Insert new row into eph table. 2574 ** if( first row of partition ){ 2575 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) 2576 ** regEnd = <expr2> 2577 ** regStart = <expr1> 2578 ** }else{ 2579 ** while( (csrEnd.key + regEnd) <= csrCurrent.key ){ 2580 ** AGGSTEP 2581 ** } 2582 ** while( (csrStart.key + regStart) < csrCurrent.key ){ 2583 ** AGGINVERSE 2584 ** } 2585 ** RETURN_ROW 2586 ** } 2587 ** } 2588 ** flush: 2589 ** while( (csrEnd.key + regEnd) <= csrCurrent.key ){ 2590 ** AGGSTEP 2591 ** } 2592 ** while( (csrStart.key + regStart) < csrCurrent.key ){ 2593 ** AGGINVERSE 2594 ** } 2595 ** RETURN_ROW 2596 ** 2597 ** RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING 2598 ** 2599 ** ... loop started by sqlite3WhereBegin() ... 2600 ** if( new partition ){ 2601 ** Gosub flush 2602 ** } 2603 ** Insert new row into eph table. 2604 ** if( first row of partition ){ 2605 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) 2606 ** regEnd = <expr2> 2607 ** regStart = <expr1> 2608 ** }else{ 2609 ** AGGSTEP 2610 ** while( (csrCurrent.key + regEnd) < csrEnd.key ){ 2611 ** while( (csrCurrent.key + regStart) > csrStart.key ){ 2612 ** AGGINVERSE 2613 ** } 2614 ** RETURN_ROW 2615 ** } 2616 ** } 2617 ** } 2618 ** flush: 2619 ** AGGSTEP 2620 ** while( 1 ){ 2621 ** while( (csrCurrent.key + regStart) > csrStart.key ){ 2622 ** AGGINVERSE 2623 ** if( eof ) break "while( 1 )" loop. 2624 ** } 2625 ** RETURN_ROW 2626 ** } 2627 ** while( !eof csrCurrent ){ 2628 ** RETURN_ROW 2629 ** } 2630 ** 2631 ** The text above leaves out many details. Refer to the code and comments 2632 ** below for a more complete picture. 2633 */ 2634 void sqlite3WindowCodeStep( 2635 Parse *pParse, /* Parse context */ 2636 Select *p, /* Rewritten SELECT statement */ 2637 WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */ 2638 int regGosub, /* Register for OP_Gosub */ 2639 int addrGosub /* OP_Gosub here to return each row */ 2640 ){ 2641 Window *pMWin = p->pWin; 2642 ExprList *pOrderBy = pMWin->pOrderBy; 2643 Vdbe *v = sqlite3GetVdbe(pParse); 2644 int csrWrite; /* Cursor used to write to eph. table */ 2645 int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */ 2646 int nInput = p->pSrc->a[0].pTab->nCol; /* Number of cols returned by sub */ 2647 int iInput; /* To iterate through sub cols */ 2648 int addrNe; /* Address of OP_Ne */ 2649 int addrGosubFlush = 0; /* Address of OP_Gosub to flush: */ 2650 int addrInteger = 0; /* Address of OP_Integer */ 2651 int addrEmpty; /* Address of OP_Rewind in flush: */ 2652 int regNew; /* Array of registers holding new input row */ 2653 int regRecord; /* regNew array in record form */ 2654 int regRowid; /* Rowid for regRecord in eph table */ 2655 int regNewPeer = 0; /* Peer values for new row (part of regNew) */ 2656 int regPeer = 0; /* Peer values for current row */ 2657 int regFlushPart = 0; /* Register for "Gosub flush_partition" */ 2658 WindowCodeArg s; /* Context object for sub-routines */ 2659 int lblWhereEnd; /* Label just before sqlite3WhereEnd() code */ 2660 int regStart = 0; /* Value of <expr> PRECEDING */ 2661 int regEnd = 0; /* Value of <expr> FOLLOWING */ 2662 2663 assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT 2664 || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED 2665 ); 2666 assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT 2667 || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING 2668 ); 2669 assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT 2670 || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES 2671 || pMWin->eExclude==TK_NO 2672 ); 2673 2674 lblWhereEnd = sqlite3VdbeMakeLabel(pParse); 2675 2676 /* Fill in the context object */ 2677 memset(&s, 0, sizeof(WindowCodeArg)); 2678 s.pParse = pParse; 2679 s.pMWin = pMWin; 2680 s.pVdbe = v; 2681 s.regGosub = regGosub; 2682 s.addrGosub = addrGosub; 2683 s.current.csr = pMWin->iEphCsr; 2684 csrWrite = s.current.csr+1; 2685 s.start.csr = s.current.csr+2; 2686 s.end.csr = s.current.csr+3; 2687 2688 /* Figure out when rows may be deleted from the ephemeral table. There 2689 ** are four options - they may never be deleted (eDelete==0), they may 2690 ** be deleted as soon as they are no longer part of the window frame 2691 ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row 2692 ** has been returned to the caller (WINDOW_RETURN_ROW), or they may 2693 ** be deleted after they enter the frame (WINDOW_AGGSTEP). */ 2694 switch( pMWin->eStart ){ 2695 case TK_FOLLOWING: 2696 if( pMWin->eFrmType!=TK_RANGE 2697 && windowExprGtZero(pParse, pMWin->pStart) 2698 ){ 2699 s.eDelete = WINDOW_RETURN_ROW; 2700 } 2701 break; 2702 case TK_UNBOUNDED: 2703 if( windowCacheFrame(pMWin)==0 ){ 2704 if( pMWin->eEnd==TK_PRECEDING ){ 2705 if( pMWin->eFrmType!=TK_RANGE 2706 && windowExprGtZero(pParse, pMWin->pEnd) 2707 ){ 2708 s.eDelete = WINDOW_AGGSTEP; 2709 } 2710 }else{ 2711 s.eDelete = WINDOW_RETURN_ROW; 2712 } 2713 } 2714 break; 2715 default: 2716 s.eDelete = WINDOW_AGGINVERSE; 2717 break; 2718 } 2719 2720 /* Allocate registers for the array of values from the sub-query, the 2721 ** samve values in record form, and the rowid used to insert said record 2722 ** into the ephemeral table. */ 2723 regNew = pParse->nMem+1; 2724 pParse->nMem += nInput; 2725 regRecord = ++pParse->nMem; 2726 regRowid = ++pParse->nMem; 2727 2728 /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING" 2729 ** clause, allocate registers to store the results of evaluating each 2730 ** <expr>. */ 2731 if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){ 2732 regStart = ++pParse->nMem; 2733 } 2734 if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){ 2735 regEnd = ++pParse->nMem; 2736 } 2737 2738 /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of 2739 ** registers to store copies of the ORDER BY expressions (peer values) 2740 ** for the main loop, and for each cursor (start, current and end). */ 2741 if( pMWin->eFrmType!=TK_ROWS ){ 2742 int nPeer = (pOrderBy ? pOrderBy->nExpr : 0); 2743 regNewPeer = regNew + pMWin->nBufferCol; 2744 if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr; 2745 regPeer = pParse->nMem+1; pParse->nMem += nPeer; 2746 s.start.reg = pParse->nMem+1; pParse->nMem += nPeer; 2747 s.current.reg = pParse->nMem+1; pParse->nMem += nPeer; 2748 s.end.reg = pParse->nMem+1; pParse->nMem += nPeer; 2749 } 2750 2751 /* Load the column values for the row returned by the sub-select 2752 ** into an array of registers starting at regNew. Assemble them into 2753 ** a record in register regRecord. */ 2754 for(iInput=0; iInput<nInput; iInput++){ 2755 sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput); 2756 } 2757 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord); 2758 2759 /* An input row has just been read into an array of registers starting 2760 ** at regNew. If the window has a PARTITION clause, this block generates 2761 ** VM code to check if the input row is the start of a new partition. 2762 ** If so, it does an OP_Gosub to an address to be filled in later. The 2763 ** address of the OP_Gosub is stored in local variable addrGosubFlush. */ 2764 if( pMWin->pPartition ){ 2765 int addr; 2766 ExprList *pPart = pMWin->pPartition; 2767 int nPart = pPart->nExpr; 2768 int regNewPart = regNew + pMWin->nBufferCol; 2769 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0); 2770 2771 regFlushPart = ++pParse->nMem; 2772 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart); 2773 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO); 2774 sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2); 2775 VdbeCoverageEqNe(v); 2776 addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart); 2777 VdbeComment((v, "call flush_partition")); 2778 sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1); 2779 } 2780 2781 /* Insert the new row into the ephemeral table */ 2782 sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid); 2783 sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid); 2784 addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid); 2785 VdbeCoverageNeverNull(v); 2786 2787 /* This block is run for the first row of each partition */ 2788 s.regArg = windowInitAccum(pParse, pMWin); 2789 2790 if( regStart ){ 2791 sqlite3ExprCode(pParse, pMWin->pStart, regStart); 2792 windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE?3:0)); 2793 } 2794 if( regEnd ){ 2795 sqlite3ExprCode(pParse, pMWin->pEnd, regEnd); 2796 windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE?3:0)); 2797 } 2798 2799 if( pMWin->eFrmType!=TK_RANGE && pMWin->eStart==pMWin->eEnd && regStart ){ 2800 int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le); 2801 int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd); 2802 VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */ 2803 VdbeCoverageNeverNullIf(v, op==OP_Le); /* values previously checked */ 2804 windowAggFinal(&s, 0); 2805 sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1); 2806 VdbeCoverageNeverTaken(v); 2807 windowReturnOneRow(&s); 2808 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr); 2809 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd); 2810 sqlite3VdbeJumpHere(v, addrGe); 2811 } 2812 if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){ 2813 assert( pMWin->eEnd==TK_FOLLOWING ); 2814 sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart); 2815 } 2816 2817 if( pMWin->eStart!=TK_UNBOUNDED ){ 2818 sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1); 2819 VdbeCoverageNeverTaken(v); 2820 } 2821 sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1); 2822 VdbeCoverageNeverTaken(v); 2823 sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1); 2824 VdbeCoverageNeverTaken(v); 2825 if( regPeer && pOrderBy ){ 2826 sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1); 2827 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1); 2828 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1); 2829 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1); 2830 } 2831 2832 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd); 2833 2834 sqlite3VdbeJumpHere(v, addrNe); 2835 2836 /* Beginning of the block executed for the second and subsequent rows. */ 2837 if( regPeer ){ 2838 windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd); 2839 } 2840 if( pMWin->eStart==TK_FOLLOWING ){ 2841 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0); 2842 if( pMWin->eEnd!=TK_UNBOUNDED ){ 2843 if( pMWin->eFrmType==TK_RANGE ){ 2844 int lbl = sqlite3VdbeMakeLabel(pParse); 2845 int addrNext = sqlite3VdbeCurrentAddr(v); 2846 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl); 2847 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); 2848 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); 2849 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext); 2850 sqlite3VdbeResolveLabel(v, lbl); 2851 }else{ 2852 windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0); 2853 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); 2854 } 2855 } 2856 }else 2857 if( pMWin->eEnd==TK_PRECEDING ){ 2858 int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE); 2859 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0); 2860 if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); 2861 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); 2862 if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); 2863 }else{ 2864 int addr = 0; 2865 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0); 2866 if( pMWin->eEnd!=TK_UNBOUNDED ){ 2867 if( pMWin->eFrmType==TK_RANGE ){ 2868 int lbl = 0; 2869 addr = sqlite3VdbeCurrentAddr(v); 2870 if( regEnd ){ 2871 lbl = sqlite3VdbeMakeLabel(pParse); 2872 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl); 2873 } 2874 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); 2875 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); 2876 if( regEnd ){ 2877 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); 2878 sqlite3VdbeResolveLabel(v, lbl); 2879 } 2880 }else{ 2881 if( regEnd ){ 2882 addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1); 2883 VdbeCoverage(v); 2884 } 2885 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); 2886 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); 2887 if( regEnd ) sqlite3VdbeJumpHere(v, addr); 2888 } 2889 } 2890 } 2891 2892 /* End of the main input loop */ 2893 sqlite3VdbeResolveLabel(v, lblWhereEnd); 2894 sqlite3WhereEnd(pWInfo); 2895 2896 /* Fall through */ 2897 if( pMWin->pPartition ){ 2898 addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart); 2899 sqlite3VdbeJumpHere(v, addrGosubFlush); 2900 } 2901 2902 addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite); 2903 VdbeCoverage(v); 2904 if( pMWin->eEnd==TK_PRECEDING ){ 2905 int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE); 2906 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0); 2907 if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); 2908 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); 2909 }else if( pMWin->eStart==TK_FOLLOWING ){ 2910 int addrStart; 2911 int addrBreak1; 2912 int addrBreak2; 2913 int addrBreak3; 2914 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0); 2915 if( pMWin->eFrmType==TK_RANGE ){ 2916 addrStart = sqlite3VdbeCurrentAddr(v); 2917 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1); 2918 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1); 2919 }else 2920 if( pMWin->eEnd==TK_UNBOUNDED ){ 2921 addrStart = sqlite3VdbeCurrentAddr(v); 2922 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1); 2923 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1); 2924 }else{ 2925 assert( pMWin->eEnd==TK_FOLLOWING ); 2926 addrStart = sqlite3VdbeCurrentAddr(v); 2927 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1); 2928 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1); 2929 } 2930 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart); 2931 sqlite3VdbeJumpHere(v, addrBreak2); 2932 addrStart = sqlite3VdbeCurrentAddr(v); 2933 addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1); 2934 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart); 2935 sqlite3VdbeJumpHere(v, addrBreak1); 2936 sqlite3VdbeJumpHere(v, addrBreak3); 2937 }else{ 2938 int addrBreak; 2939 int addrStart; 2940 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0); 2941 addrStart = sqlite3VdbeCurrentAddr(v); 2942 addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1); 2943 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); 2944 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart); 2945 sqlite3VdbeJumpHere(v, addrBreak); 2946 } 2947 sqlite3VdbeJumpHere(v, addrEmpty); 2948 2949 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr); 2950 if( pMWin->pPartition ){ 2951 if( pMWin->regStartRowid ){ 2952 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid); 2953 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid); 2954 } 2955 sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v)); 2956 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart); 2957 } 2958 } 2959 2960 #endif /* SQLITE_OMIT_WINDOWFUNC */ 2961