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