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